繁体   English   中英

使用 spring 创建多个 kafka 主题

[英]creating multiple kafka topics using spring

我正在创建一个 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;

}

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

@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);
    }
  }
}

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

暂无
暂无

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

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