Home > database >  Multiple @ManagedListener s for different Kafka topics calling the same method
Multiple @ManagedListener s for different Kafka topics calling the same method

Time:11-14

The existing code I’m working with is creating a new method with duplicate code each time because it is using @ManagedListener configured for the different Kafka Topics and diff configurations using Java Spring Boot.

`@ManagedListener({configurations for Kafka topic-a})
method1(){
//logic to handle data
}

@ManagedListener({configurations for Kafka topic-b})
method2(){
//same logic as method1 copied
}

@ManagedListener({configurations for Kafka topic-c})
method3(){
//same logic as method1 copied again
}`

Is there a way I can have a listener configured to different Kafka topics configurations that all call method1 directly? I’m trying to find a way to avoid duplicate code.

I tried to add multiple @managedListener annotations to the same method, but it seems like it has to be one to one. It will work if I duplicate the code, but it seems counterintuitive

The expected result is to be able to receive messages from multiple different Kafka topics.

CodePudding user response:

I'm not sure about @ManagedListener usage here since @KafkaListener is what's more commonly used to setup a Kafka consumer. This annotation already supports consuming multiple topics on its own (assuming same consumer config factory), so you wouldn't need multiple methods anyway.

But the annotations don't prevent you from calling any common methods.

I'd suggest extracting all common logic to a function that is not annotated as a Kafka listener, however.

CodePudding user response:

I don't know what @ManagedListener is, but @KafkaListener is a @Repeatable annotation (you can put multiple annotations on a method).

  • Related