[英]Enabling @KafkaListener to take in variable topic names from application.yml file
I am attempting to load in multiple topics to a single @KafkaListener
but am running into trouble as I believe it is looking for a constant value, but initializing the topics
variable from the application.yml
file causing something issues, I was wondering if someone could help me troubleshoot this issue, or provide me with direction into how to load multiple Kafka topics into a single KafkaListener. 我试图在多个主题加载到一个@KafkaListener
但我遇到了麻烦,因为我相信它正在寻找一个恒定值,但初始化topics
从变量application.yml
文件造成什么问题,我如果有人能够知道帮助我解决此问题,或为我提供有关如何将多个Kafka主题加载到单个KafkaListener中的指导。
I am able to listen to multiple topics in the same @KafkaListener
by passing them in a comma delimited object as seen below: 通过将它们传递@KafkaListener
逗号分隔的对象,我可以在同一个@KafkaListener
收听多个主题,如下所示:
@KafkaListener(topics = {
"flight-events",
"flight-time-events",
"service-events",
"flight-delay-events"
})
I realize I could do an object with comma delimited values representing the topics, but I want to be able to add topics through a config file, rather than changing code in the code base. 我意识到我可以用逗号分隔的值表示主题的对象,但是我希望能够通过配置文件添加主题,而不是更改代码库中的代码。
I believe there may be the problem in that @KafkaListener needs to take in a constant value, and I am unable to define an annotation as a constant, is there any way around this? 我相信可能存在问题,因为@KafkaListener需要采用一个常量值,而我无法将注释定义为常量,对此有什么办法吗?
KafkaWebSocketConnector.java
@Component
public class KafkaWebSocketConnector
{
@Value("${spring.kafka.topics}")
private String[] topics;
@KafkaListener(topics = topics)
public void listen(ConsumerRecord<?, Map<String, String>> message)
{
log.info("Received messages on topic [{}]: [{}]", message.topic(), message.value());
String dest = "/" + message.topic();
log.info("destination = {}", dest);
log.info("msg: {}", message);
messageTemplate.convertAndSend(dest, message.value());
}
}
application.yml
spring:
kafka:
consumer:
auto-offset-reset: earliest
group-id: kafka-websocket-connector
topics: flight-events,
flight-time-events,
canceled-events,
pax-events,
flight-delay-events
Answer provided from @Gary Russell from this GitHub issue: @Gary Russell从此GitHub问题提供的答案:
https://github.com/spring-projects/spring-kafka/issues/361 https://github.com/spring-projects/spring-kafka/issues/361
You can use a SpEL expression; 您可以使用SpEL表达式; there's an example in EnableKafkaIntegrationTests... 在EnableKafkaIntegrationTests中有一个示例...
@KafkaListener(id = "foo", topics = "#{'${topicOne:annotated1,foo}'.split(',')}")
In my case "#{'${spring.kafka.topics}'.split(',')}"
在我的情况下为"#{'${spring.kafka.topics}'.split(',')}"
I was able to implement the above code, (provided by Gary Russell) in order to answer the above question. 为了回答上述问题,我能够实现上述代码(由Gary Russell提供)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.