Kafka Topic Creation using Spring Boot

Viewed 1555

I am trying to create a new topic in Kafka Using Spring Boot.

Upon Searching in Google, I got the below answer

@Configuration
public class KafkaTopicConfiguration {
  
  @Bean
  public NewTopic createTopic(Topic topic) {
    return TopicBuilder.name(topic.getTopicName())
      .partitions(topic.getPartitions())
      .replicas(topic.getReplicas())
      .build();
  }
}

But I am not able to implement the following using Spring Boot REST POST Call.

    @PostMapping("/api/v1/kafkatopic/")
    public NewTopic createTopic(@RequestBody Topic topic)
    {
        return kt.createTopic(topic);
    }

//kt being object of the Configuration Class

But the same code works if the topic details have been passed along the code (hardcoded) like below.

  @Bean
  public NewTopic createTopic() {
    return TopicBuilder.name("test-topic")
      .partitions(6)
      .replicas(3)
      .build();
  }

Could someone please help.

Thanks in advance

1 Answers

NewTopic beans are only created during application initialization. Calling the bean factory method at runtime does nothing.

To dynamically create topics, you need to use an AdminClient. Spring Boot auto-configures a KafkaAdmin bean.

You can create an AdminClient using its properties.

Then use the client to create your topic(s).

try (AdminClient client = AdminClient.create(kafkaAdmin.getConfigurationProperties()) {
    ...
}
Related