life is too short for a diary




How to Listen to a Kafka Consumer in Spring Boot (Reactive & Non-Reactive)

Tags: java spring boot kafka

Author
Written by: Tushar Sharma
Featured image for How to Listen to a Kafka Consumer in Spring Boot (Reactive & Non-Reactive)

In a traditional servlet based Spring boot, you can use KafkaListener annotation

@Service
public class MyService {
    @KafkaListener(topics = "myTopic") 
    public void listen(ConsumerRecord<String, String> record) {
        // process the record
    }
}

Pros:

Cons:

Reactive Kafka Consumer with Project Reactor

ApplicationEventListener

@Service
public class MyService {
    @Autowired
    private ReactiveKakfaConsumer<String, String> ReactiveKakfaConsumer;


    @EventListener(ApplicationReadyEvent.class)
    public void listen() {
        ReactiveKakfaConsumer
          .reactive()
            .subscribe( record -> {
                // process the message
            }, error -> {

            });
    }
}

PostConstruct

@Service
public class MyService {
    @Autowired
    private ReactiveKakfaConsumer<String, String> ReactiveKakfaConsumer;


    @PostConstruct
    public void listen() {
        ReactiveKakfaConsumer
          .reactive()
            .subscribe( record -> {
                // process the message
            }, error -> {

            });
    }
}

CommanLineRunner

@Service
public class MyService implements CommanLineRunner {
    @Autowired
    private ReactiveKakfaConsumer<String, String> ReactiveKakfaConsumer;


    @Override
    public void run(String... args) {
        ReactiveKakfaConsumer
          .reactive()
            .subscribe( record -> {
                // process the message
            }, error -> {

            });
    }
}

When to use Each Approach

PostConstruct When you need initialization right after bean creation Triggered immediately after bean construction and dependency injection
CommnadLineRunner When you need to run code after the application context is fully started Executes after the application context is ready but before the application start
ApplicationReadyEvent When you need to ensure all aspects of application are ready Trigger after the application is started and ready to server the request

comments powered by Disqus