java - 使用spring创建多个kafka主题

标签 java spring-boot apache-kafka

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

关于java - 使用spring创建多个kafka主题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56770412/

相关文章:

java - Spring Boot - 与 Material UI 进行 react

apache-kafka - 在 docker-desktop k8s 集群上运行 strimzi 时找不到 Kafka 主题

java - Kafka KStreams - 如何添加线程/使用 StreamsConfig.NUM_STREAM_THREADS_CONFIG

java - 拦截器没有被调用

spring - 为什么 AuthenticationManager 会抛出 StackOverflowError?

java - IBM Websphere 应用程序服务器上的应用程序出现 Kafka SSL 连接问题

java - 读取与精确日期模式 YYYY-MM-DD 匹配的输入

java - 具有合法索引、java、imagej 的 ArrayIndexOutOfBoundsException

Java:如何在运行时使用可变参数正确构造正则表达式

java - 与使用 setter 函数实现的注入(inject)捆绑在一起