使用 spring @Bean 创建 kafka 主题?

creating kafka topic using spring @Bean?

是否可以使用 spring bean 创建 kafka 主题。就像我们在 RabbitMQ 中有 Queue 和 TopicExchanges 一样,它们可以像这样以编程方式创建。

@Bean
Queue queue(){
  return new Queue("name");
}

尝试了文档无法获得太多帮助。

是的,现在可以使用最新的 Spring Kafka 版本 1.3https://docs.spring.io/spring-kafka/docs/1.3.0.RC1/reference/html/_reference.html#_configuring_topics

@Bean
public KafkaAdmin admin() {
    Map<String, Object> configs = new HashMap<>();
    configs.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG,
            StringUtils.arrayToCommaDelimitedString(kafkaEmbedded().getBrokerAddresses()));
    return new KafkaAdmin(configs);
}

@Bean
public NewTopic topic1() {
     return new NewTopic("foo", 10, (short) 2);
}

但请注意,由于 Apache Kafka 0.11.0.x 改进,这是可能的。

版本 2.3 引入了一个新的 class TopicBuilder 来使创建这样的 beans 更方便:configuring-topics

If you define a KafkaAdmin bean in your application context, it can automatically add topics to the broker. To do so, you can add a NewTopic @Bean for each topic to the application context. Version 2.3 introduced a new class TopicBuilder to make creation of such beans more convenient. The following example shows how to do so:

@Bean
public KafkaAdmin admin() {
    Map<String, Object> configs = new HashMap<>();
    configs.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, ...);
    return new KafkaAdmin(configs);
}

@Bean
public NewTopic topic1() {
    return TopicBuilder.name("thing1")
            .partitions(10)
            .replicas(3)
            .compact()
            .build();
}