[英]How to pass dynamic topic name to @KafkaListener(topics) from environment variable
I'm writing a Kafka consumer.我正在写一个 Kafka 消费者。 I need to pass the environment variable topic name to @KafkaListener(topics = ...)
.我需要将环境变量主题名称传递给@KafkaListener(topics = ...)
。 This is what I have tried so far:这是我到目前为止所尝试的:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;
@Service
public class KafkaConsumer {
@Autowired
private EnvProperties envProperties;
private final String topic = envProperties.getTopic();
@KafkaListener(topics = "#{'${envProperties.getTopic()}'}", groupId = "group_id")
public void consume(String message) {
logger.info("Consuming messages " +envProperties.getTopic());
}
}
I'm getting an error at the line topics = "#{'${envProperties.getTopic()}'}"
, the application fails to start.我在topics = "#{'${envProperties.getTopic()}'}"
行遇到错误,应用程序无法启动。
How to set this topic name dynamically from the environment variable?如何从环境变量中动态设置此主题名称?
Normally, you can't reference fields or properties from the bean in which the SpEL is declared.通常,您不能从声明 SpEL 的 bean 中引用字段或属性。 However, @KafkaListener
has special syntax to support it.但是, @KafkaListener
有特殊的语法来支持它。
See the documentation . 请参阅文档。
Starting with version 2.1.2, the SpEL expressions support a special token
__listener
which is a pseudo bean name which represents the current bean instance within which this annotation exists.从版本 2.1.2 开始,SpEL 表达式支持一个特殊的标记__listener
,它是一个伪 bean 名称,表示存在此注释的当前 bean 实例。
So, if you add public EnvProperties getEnvProperties()
to the class then something like因此,如果您将public EnvProperties getEnvProperties()
添加到类中,则类似于
#{__listener.envProperties.topic}
should work.应该管用。
In KafkaConsumer class, you need to make below changes :在 KafkaConsumer 类中,您需要进行以下更改:
@Autowired
public EnvProperties envProperties;
@KafkaListener(topics = "#{kafkaConsumer.envProperties.getTopic()}"
It worked for me.它对我有用。
If you are looking to set topic as an environmental variable, you can pass the topic below如果您希望将主题设置为环境变量,您可以传递下面的主题
@KafkaListener(topics = "#{systemEnvironment['TOPIC']}")
Then you can set topic as below,然后你可以设置如下主题,
export TOPIC=mytopic
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.