如何将动态主题名称从环境变量传递给@KafkaListener(topics) [英] How to pass dynamic topic name to @KafkaListener(topics) from environment variable

查看:754
本文介绍了如何将动态主题名称从环境变量传递给@KafkaListener(topics)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个卡夫卡消费者.我需要将环境变量主题名称传递给@KafkaListener(topics = ...).到目前为止,这是我尝试过的:

I'm writing a Kafka consumer. I need to pass the environment variable topic name to @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());
     }
}

我在topics = "#{'${envProperties.getTopic()}'}"行出现错误,应用程序无法启动.

I'm getting an error at the line topics = "#{'${envProperties.getTopic()}'}", the application fails to start.

如何通过环境变量动态设置此主题名称?

How to set this topic name dynamically from the environment variable?

推荐答案

在KafkaConsumer类中,您需要进行以下更改:

In KafkaConsumer class, you need to make below changes :

@Autowired
public EnvProperties envProperties;

@KafkaListener(topics = "#{kafkaConsumer.envProperties.getTopic()}"

对我有用.

这篇关于如何将动态主题名称从环境变量传递给@KafkaListener(topics)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆