问题
I want to be able to read in topics through the properties without specifying anything on the Kafka listener annotation. Not using Spring Boot.
I tried having the topics read straight from the properties object via a "topics" key. That gives an error: IllegalStateException:topics, topicPattern, or topicPartitions must be provided.
// some class
@KafkaListener
public void listener(List<String> messages) {
System.out.print(messages);
}
//some other class
@Bean
public ConsumerFactory<String, String> consumerFactory(Properties topicProp) {
return new DefaultKafkaConsumerFactory(topicProp);
}
@Bean
public ConcurrentKafkaListenerContainerFactory<String, String> kafkaListenerContainerFactory() {
ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
Properties prop = new Properties();
prop.setProperty("topics", "my-custom-topic");
factory.setConsumerFactory(this.consumerFactory(prop));
return factory;
}
Is this possible?
回答1:
You can reference other beans (or methods on beans) in topics
@Bean
public String topicName() {
return "my-custom-topic";
}
...
@KafkaListener(topics = "#{@topicName}")
...
or
@KafkaListener(topics = "#{@someBean.someMethod()}")
来源:https://stackoverflow.com/questions/57064593/how-do-i-configure-spring-kafka-listener-for-a-specfic-topic-using-the-factory