Search code examples
kotlinapache-kafkamicronaut

Do I need a background job to consume messages from Kafka?


Is it necessary to run a background job to continuously consume messages from Kafka's topic?

I'm trying to write an application using Micronaut in Kotlin as Kafka Consumer, is there any way to consume messages from Kafka without running a background job?


Solution

  • You don't need implement a background job yourself. Leave this to the framework.

    All you need to do is define a Micronaut bean as a KafkaListener. The documentation states as follows:

    Using the @KafkaListener annotation Micronaut will build a KafkaConsumer and start the poll loop by running the KafkaConsumer in a special consumer thread pool

    So what you should do is

    @KafkaListener
    class MyKafkaListener {
    
        @Topic("topic-you-want-to-listen-to")
        fun receive(@KafkaKey brand: String, name: String) { 
          // implement your listener
        }
    }
    

    Hope this helps as a brief clarification.