The following is a simple example of implementing a message queue using Spring Boot and Kafka:
- Introduce dependencies
Add the following dependencies in pom.xml:
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
<version>2.7.5</version>
</dependency>
- Place Kafka
Add Kafka related configuration in application.properties:
spring.kafka.bootstrap-servers=localhost:9092
spring.kafka.consumer.group-id=myGroup
spring.kafka.producer.key-serializer=org.apache.kafka.common.serialization.StringSerializer
spring.kafka.producer.value-serializer=org.apache.kafka.common.serialization.StringSerializer
spring.kafka.consumer.key-deserializer=org.apache.kafka.common.serialization.StringDeserializer
spring.kafka.consumer.value-deserializer=org.apache.kafka.common.serialization.StringDeserializer
- Send a message
Create a producer class and use KafkaTemplate to send messages:
@Service
public class KafkaProducerService {
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
public void sendMessage(String topic, String message) {
kafkaTemplate.send(topic, message);
}
}
- receive messages
Create a consumer class, use the @KafkaListener annotation to listen to the specified topic and process messages:
@Service
public class KafkaConsumerService {
@KafkaListener(topics = "myTopic", groupId = "myGroup")
public void onMessage(String message) {
System.out.println("Received message: " + message);
}
}
- test
Call the producer in the Controller to send the message, and then you can see the message received by the consumer in the console:
@RestController
public class KafkaController {
@Autowired
private KafkaProducerService kafkaProducerService;
@GetMapping("/send")
public String sendMessage() {
kafkaProducerService.sendMessage("myTopic", "Hello, Kafka!");
return "Message sent successfully";
}
}
The above is a simple example of using Spring Boot and Kafka to implement a message queue.
Partition
- Write Kafka producer code, use KafkaTemplate to send messages, and specify the partition number. As follows:
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
public void sendMessage(String message, int partition) {
kafkaTemplate.send("my-topic", partition, null, message);
2. Write Kafka consumer code, use the @KafkaListener annotation to listen to the specified topic, and obtain the partition number in the method parameters. As follows:
@KafkaListener(topics = "my-topic", groupId = "my-group")
public void listen(ConsumerRecord<String, String> record, @Header(KafkaHeaders.RECEIVED_PARTITION_ID) int partition) {
System.out.println("Received message: " + record.value() + ", partition: " + partition);