如何使用工厂为特定主题配置Spring Kafka Listener?

时间:2019-07-16 19:57:00

标签: java spring apache-kafka kafka-consumer-api spring-kafka

我希望能够通过属性读取主题,而无需在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?

1 个答案:

答案 0 :(得分:3)

您可以在topics中引用其他bean(或bean上的方法)

@Bean
public String topicName() {
    return "my-custom-topic";
}

...

@KafkaListener(topics = "#{@topicName}")
...

@KafkaListener(topics = "#{@someBean.someMethod()}")