简体   繁体   English

我可以在运行时向我的@kafkalistener 添加主题吗

[英]Can i add topics to my @kafkalistener at runtime

I have created a bean for the topic array and at runtime i added some topics to this topic array but the consumer did not update the topic and still consuming from the first topics inside the topic array.我为主题数组创建了一个 bean,在运行时我向这个主题数组添加了一些主题,但是消费者没有更新主题,并且仍然从主题数组中的第一个主题中消费。 i would like that the consumer added these new topic and start consuming from them我希望消费者添加这些新主题并开始从中消费

@Autowired
private String[] topicArray;

@KafkaListener(topics = "#{topicArray}", groupId = "MyGroup")
    public void listen(...) {
        ...
    }

No;不; the property is evaluated once, during initialization.该属性在初始化期间被评估一次。

You cannot add topics to an existing listener container at runtime.您不能在运行时将主题添加到现有的侦听器容器。

You can, however, make your listener bean a prototype bean and create a new container each time you want to listen to new topics.但是,您可以使您的侦听器 bean 成为原型 bean,并在每次您想收听新主题时创建一个新容器。

Here's an example:这是一个例子:

@SpringBootApplication
public class So68744775Application {

    public static void main(String[] args) {
        SpringApplication.run(So68744775Application.class, args);
    }

    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    Foo foo(String id, String[] topics) {
        return new Foo(id, topics);
    }

    @Bean
    public ApplicationRunner runner(ApplicationContext context) {
        return args -> {
            context.getBean(Foo.class, "one", new String[] { "topic1", "topic2" });
            context.getBean(Foo.class, "two", new String[] { "topic3" });
        };
    }

}

class Foo {

    private final String id;

    private final String[] topics;

    public Foo(String id, String[] topics) {
        this.id = id;
        this.topics = topics;
    }

    public String getId() {
        return this.id;
    }

    public String[] getTopics() {
        return this.topics;
    }

    @KafkaListener(id = "#{__listener.id}", topics = "#{__listener.topics}")
    public void listen(String in) {
        System.out.println(in);
    }

}

Note that it is better, however, to omit the groupId so each container is in its own group (the id property).但是请注意,最好省略groupId ,这样每个容器都在自己的组中( id属性)。 This avoids an unnecessary rebalance when the new container is added.这避免了在添加新容器时不必要的重新平衡。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM