如何将动态主题名称传递给@kafkalistener(环境变量中的主题 [英] How to pass dynamic topic name to @kafkalistener(topics from environment variable
问题描述
我正在写卡夫卡消费者 我想将环境变量主题名称传递给@kafkalistener(topics = topic
I AM WRITING A KAFKA CONSUMER I want to pass the environment variable topic name to @kafkalistener(topics = topic
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());
}
}
topics =#{'$ {envProperties.getTopic()}'}" 在这条线 抛出错误.我的应用程序无法启动.必须根据环境变量动态设置此主题名称.
topics = "#{'${envProperties.getTopic()}'}" AT THIS LINE IT IS THROWING ERROR . MY APPLICATION FAILS TO START. hOW TO SET THIS TOPIC NAME DYNAMICALLY FROM ENVIRONMENT VARIABLE.
推荐答案
通常,您不能从声明SpEL的bean中引用字段或属性.但是,@KafkaListener
具有支持它的特殊语法.
Normally, you can't reference fields or properties from the bean in which the SpEL is declared. However, @KafkaListener
has special syntax to support it.
从版本2.1.2开始,SpEL表达式支持特殊的标记
__listener
,这是一个伪bean名称,代表该注释所在的当前bean实例.
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.
因此,如果将public EnvProperties getEnvProperties()
添加到类中,则类似
So, if you add public EnvProperties getEnvProperties()
to the class then something like
#{__listener.envProperties.topic}
应该工作.
这篇关于如何将动态主题名称传递给@kafkalistener(环境变量中的主题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!