【问题标题】:creating multiple kafka topics using spring使用spring创建多个kafka主题
【发布时间】:2019-11-08 06:11:49
【问题描述】:

我正在创建一个 spring-boot 应用程序,它将创建多个主题。我从 .csv 文件中获取主题名称和配置列表。我正在尝试这段代码,但它只能创建一个主题,但不利于使用它创建多个主题。有没有办法使用 spring 创建多个主题?

@Bean
public KafkaAdmin admin(){
    Map<String, Object> configs = new HashMap<>();
    configs.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG,"localhost:9092");
    return new KafkaAdmin(configs);
}
@Bean
public NewTopic topic1() {
        NewTopic topic = new NewTopic(String.format("topic%d",1), 10, (short) 1);
        Map<String, String> extraTopicConfig = new HashMap<String, String>();
        extraTopicConfig.put(TopicConfig.CLEANUP_POLICY_CONFIG, "compact");
        extraTopicConfig.put(TopicConfig.MIN_IN_SYNC_REPLICAS_CONFIG, "1");
        topic.configs(extraTopicConfig);
        return topic;

}

【问题讨论】:

    标签: java spring-boot apache-kafka


    【解决方案1】:

    对于在启动期间难以以编程方式创建多个主题或在不同代理上创建主题的任何人,请考虑使用 ApplicationRunner。类似于已接受的答案here 中描述的内容。

    【讨论】:

      【解决方案2】:

      我遇到了这个老问题,正在寻找答案。 我是这样解决的:

      @Configuration
      public class TopicCreation {
        final String[] topicNames = new String[] {"topic1", "topic2"};
        final SingletonBeanRegistry beanRegistry;
      
        public TopicCreation(GenericApplicationContext context) {
          this.beanRegistry = context.getBeanFactory();
        }
      
        @PostConstruct
        public void createTopics() {
          for (String topic : topicNames) {
            NewTopic newTopic = TopicBuilder.name(topic)
                .replicas(1)
                .partitions(1)
                .build();
            beanRegistry.registerSingleton("topic-" + topic, newTopic);
          }
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-07-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-10
        • 1970-01-01
        相关资源
        最近更新 更多