使用spring创建多个kafka主题

k2arahey  于 2021-06-06  发布在  Kafka
关注(0)|答案(1)|浏览(385)

我正在创建一个spring启动应用程序,它将创建多个主题。我从.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;

}
pinkon5k

pinkon5k1#

我突然想到这个老问题,想找个答案。我是这样解决的:

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

相关问题