我希望能够通过属性读取主题,而无需在Kafka侦听器注释上指定任何内容。不使用Spring Boot。
我尝试通过“ topics”键直接从属性对象读取主题。出现错误: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?
答案 0 :(得分:3)
您可以在topics
中引用其他bean(或bean上的方法)
@Bean
public String topicName() {
return "my-custom-topic";
}
...
@KafkaListener(topics = "#{@topicName}")
...
或
@KafkaListener(topics = "#{@someBean.someMethod()}")