一个Spring的KafkaConsumer监听器可以监听多个主题吗?

R.C*_*R.C 5 spring spring-boot spring-kafka

任何人都知道单个监听器是否可以监听下面的多个主题?我知道只有"topic1"有效,如果我想添加其他主题怎么办?你能否在下面展示两个例子?谢谢您的帮助!

@KafkaListener(topics = "topic1,topic2")
public void listen(ConsumerRecord<?, ?> record, Acknowledgment ack) {
    System.out.println(record);
} 
Run Code Online (Sandbox Code Playgroud)

要么

ContainerProperties containerProps = new ContainerProperties(new TopicPartitionInitialOffset("topic1, topic2", 0));
Run Code Online (Sandbox Code Playgroud)

Art*_*lan 9

是的,只需遵循@KafkaListenerJavaDocs:

/**
 * The topics for this listener.
 * The entries can be 'topic name', 'property-placeholder keys' or 'expressions'.
 * Expression must be resolved to the topic name.
 * Mutually exclusive with {@link #topicPattern()} and {@link #topicPartitions()}.
 * @return the topic names or expressions (SpEL) to listen to.
 */
String[] topics() default {};

/**
 * The topic pattern for this listener.
 * The entries can be 'topic name', 'property-placeholder keys' or 'expressions'.
 * Expression must be resolved to the topic pattern.
 * Mutually exclusive with {@link #topics()} and {@link #topicPartitions()}.
 * @return the topic pattern or expression (SpEL).
 */
String topicPattern() default "";

/**
 * The topicPartitions for this listener.
 * Mutually exclusive with {@link #topicPattern()} and {@link #topics()}.
 * @return the topic names or expressions (SpEL) to listen to.
 */
TopicPartition[] topicPartitions() default {};
Run Code Online (Sandbox Code Playgroud)

所以,你的用例应该是这样的:

@KafkaListener(topics = {"topic1" , "topic2"})
Run Code Online (Sandbox Code Playgroud)

  • 对于另一种情况,您需要为每个主题分配一个“TopicPartitionInitialOffset”。 (2认同)

Kum*_*mar 5

如果我们必须从 application.properties 文件中获取多个主题:

@KafkaListener(topics = { "${spring.kafka.topic1}", "${spring.kafka.topic2}" })
Run Code Online (Sandbox Code Playgroud)