How do I configure Spring Kafka Listener for a specfic topic using the factory?

假如想象 提交于 2020-12-02 00:16:19

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!