SpringKafka动态指定@KafkaListener的topics和groupId

1.@KafkaListener

@KafkaListener是kafka的消费者,topics是其主题名,groupId是组名; 属性值一般只支持常量,再集群的情况下,topics、groupId如果不是动态的,那集群环境中只有一台能消费同主题上的任务;

2.动态指定 topics、groupId两个属性

@KafkaListener中有一个beanRef属性,专门获取spring容器中的bean; beanRef:此注释中的SpEL表达式中使用的伪bean名称,用于引用定义此侦听器的当前bean。这允许访问封闭bean中的属性和方法。默认的__listener。 指定beanRef属性后,即可使用bean实例动态指定topics、groupId两个属性;

例子:

参数对象

public class Listener {
    private List<String> topicList;
    private String group;

    public Listener(List<String> topicList, String group) {
        this.topicList = topicList;
        this.group = group;
    }

    public List<String> getTopicList() {
        return topicList;
    }

    public void setTo
经验分享 程序员 微信小程序 职场和发展