How to pass dynamic topic name to @kafkalistener(topics from environment variable

烂漫一生 提交于 2020-02-25 09:38:32

问题


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()}'}" AT THIS LINE IT IS THROWING ERROR . MY APPLICATION FAILS TO START. hOW TO SET THIS TOPIC NAME DYNAMICALLY FROM ENVIRONMENT VARIABLE.


回答1:


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.

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.

So, if you add public EnvProperties getEnvProperties() to the class then something like

#{__listener.envProperties.topic}

should work.



来源:https://stackoverflow.com/questions/54038928/how-to-pass-dynamic-topic-name-to-kafkalistenertopics-from-environment-variabl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!