Milan Rathod
Milan Rathod

Reputation: 33

Single KafkaListener for multiple consumer factory

I have two kafka consumer factories defined in the spring boot application with both pointing to different kafka clusters. kafkaListenerContainerFactory and otherKafkaListenerContainerFactory.

And to listen to messages published from both the kafka servers i have to define two listener methods and marked them with @KafkaListener annotation and specify topic and containerFactory attributes.

Check out below sample code.

@KafkaListener(topics = "test-topic", containerFactory = "otherKafkaListenerContainerFactory")
public void listenTestEvent(ConsumerRecord<String, String> record) {
   // Same logic as below method
}

@KafkaListener(topics = "test-topic", containerFactory = "kafkaListenerContainerFactory")
public void listenTestEventServer2(ConsumerRecord<String, String> record) {
   // Same logic as above method
}

Is there any way to combine the above two listeners methods together by specifying the array of container factories?

Upvotes: 0

Views: 832

Answers (1)

Artem Bilan
Artem Bilan

Reputation: 121462

No, it was not designed for such a heterogeneous complexity. In the end it creates a KafkaConsumer for particular cluster and inject your method for consumption. As far as I remember Hibernate, you can have only one-to-one mapping from your entity to to the target table in DB.

So, you can have those simple methods with different annotation, but delegate from both of them to the same service method.

Or you can spawn several instances of your microservice to point to different Kafka clusters. This way you won't need to change anything in the code and would have only one @KafkaListener.

Upvotes: 0

Related Questions