如何在springboot中动态地为每个主题创建单独的Kafka监听器?

Yas*_*nth 8 spring spring-mvc spring-boot kafka-consumer-api spring-kafka

我是Spring和Kafka的新手.我正在研究一个用例[使用SpringBoot-kafka],允许用户在运行时创建kafka主题.spring应用程序应该在运行时以编程方式订阅这些主题.到目前为止我所知道的是,Kafka听众是设计时间,因此需要在启动前指定主题.有没有办法动态订阅SpringBoot-Kafka集成中的kafka主题?

推荐这个 https://github.com/spring-projects/spring-kafka/issues/132

我计划实现的当前方法是,不要使用Spring-Kafka集成而不是自己实现Kafka消费者[使用java代码]如此处提到的 spring boot kafka consumer - 如何正确地使用来自spring boot的kafka消息

mic*_*brz 6

如果您想使用注释指定它们,Kafka听众只是"设计时间".Spring-kafka允许您动态创建它们,请参阅KafkaMessageListenerContainer.

动态创建的Kafka监听器的最简单示例是:

Map<String, Object> consumerConfig = ImmutableMap.of(
    BOOTSTRAP_SERVERS_CONFIG, "brokerAddress",
    GROUP_ID_CONFIG, "groupId"
);

DefaultKafkaConsumerFactory<String, String> kafkaConsumerFactory =
        new DefaultKafkaConsumerFactory<>(
                consumerConfig,
                new StringDeserializer(),
                new StringDeserializer());

ContainerProperties containerProperties = new ContainerProperties("topicName");
containerProperties.setMessageListener((MessageListener<String, String>) record -> {
     //do something with received record
} 

ConcurrentMessageListenerContainer container =
        new ConcurrentMessageListenerContainer<>(
                kafkaConsumerFactory,
                containerProperties);

container.start();
Run Code Online (Sandbox Code Playgroud)

有关更多说明和代码,请参阅此博客文章:http://www.douevencode.com/articles/2017-12/spring-kafka-without-annotations/