Kafka Listner annotation is a powerful addition to the suite of annotations available in Spring Boot. It allows developers to efficiently subscribe to multiple topics so that they can process the messages more quickly and easily. With this annotation, developers can save time, improve the performance of their applications, and make efficient use of their development resources. In this blog post, we’ll discuss how to subscribe multiple topics using @KafkaListner annotation in Spring Boot and the various benefits it offers. We’ll also look at the steps required to set up the annotation and how to properly use it in code. By the end of this post, you should have a better understanding of how @KafkaListner annotation simplifies the development process and how it can improve your applications. So, let’s get started!
@KafkaListener(topics = {"topic1" , "topic2"})
If we have to fetch multiple topics from the application.properties file :
@KafkaListener(topics = { "${spring.kafka.topic1}", "${spring.kafka.topic2}" })
You can use
@KafkaListener(topics = "#{'${kafka.topics}'.split(',')}"
where kafka.topics
is taken from your property file and contains the comma separated topics to which your listener should listen to.
Regarding the subscription of multuiple topics, you can use topicPatterns to achieve that:
@KafkaListener(topicPattern = "com.customer.*")
Regarding the programmatic access to the topic name, you can use @Header annotated method to extract a specific header value, defined by KafkaHeaders, which in your case is RECEIVED_TOPIC:
The header containing the topic from which the message was received.
@KafkaListener(topics = "com.customer.nike")
public void receive(String payload, @Header(KafkaHeaders.RECEIVED_TOPIC) String topic) {
LOGGER.info("received payload='{}'", payload);
LOG.info("received from topic: {}", topic);
}