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

Can a single Spring's KafkaConsumer listener listens to multiple topic?

有人知道单个听众是否可以像下面这样收听多个主题?我只知道 "topic1" 有效,如果我想添加其他主题怎么办?你能在下面举出这两个例子吗?感谢您的帮助!

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

ContainerProperties containerProps = new ContainerProperties(new TopicPartitionInitialOffset("topic1, topic2", 0));

是的,只需遵循 @KafkaListener JavaDocs:

/**
 * 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 {};

所以,你的 use-case 应该是这样的:

@KafkaListener(topics = {"topic1" , "topic2"})

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

@KafkaListener(topics = { "${spring.kafka.topic1}", "${spring.kafka.topic2}" })