11

我是 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 消息

4

1 回答 1

10

如果您想使用注释指定 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();

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

于 2017-12-29T11:44:31.630 回答