集成Spring Boot和Reactor-Kafka的KafkaReceiver

时间:2019-03-19 13:48:01

标签: java spring spring-boot project-reactor spring-kafka

我正在尝试使用reactor-kafka库开发一个Spring Boot应用程序,以对从Kafka主题读取的某些消息做出反应。

我有一个配置类,可以构建KafkaReceiver

@Configuration
public class MyConfiguration {

    @Bean
    public KafkaReceiver<String, String> kafkaReceiver() {
        Map<String, Object> props = new HashMap<>();
        // Options initialisation...
        final ReceiverOptions<String, String> receiverOptions =
                ReceiverOptions.<String, string>create(props)
                               .subscription(Collections.singleton(consumer.getTopic()));
        return KafkaReceiver.create(receiverOptions);
    } 
}

嗯...现在呢?使用不太活跃的spring-kafka库,我可以用@KafkaListener注释一个方法,Spring Boot会为我创建一个监听Kafka主题的线程。

应该将KafkaReceiver放在哪里?在所有示例中,我发现直接使用main方法,但这不是引导方式

我正在使用Spring Boot 2.1.3和Reactor-Kafka 1.1.0

谢谢。

1 个答案:

答案 0 :(得分:2)

Since you have that KafkaReceiver bean, now you can do like this:

@Bean
public ApplicationRunner runner(KafkaReceiver<String, String> kafkaReceiver) {
        return args -> {
                kafkaReceiver.receive()
                          ...
                          .sunbscribe();
        };
}

This ApplicationRunner bean is going to be kicked when the ApplicationContext is ready. See its JavaDocs for more info.