To create a Kafka topic in Spring Boot, you can use the AdminClient
class provided by the Kafka client library. Here's an example of how you can do it:
import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.NewTopic;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public NewTopic createTopic() {
return new NewTopic("my-topic", 1, (short) 1);
}
@Bean
public AdminClient adminClient(KafkaProperties properties) {
Map<String, Object> configs = new HashMap<>(properties.buildAdminProperties());
return AdminClient.create(configs);
}
}
The createTopic()
method creates a NewTopic
object representing the topic you want to create. The adminClient()
method creates an AdminClient
object, which you can use to create the topic.
To actually create the topic, you can use the createTopics()
method of the AdminClient
object. Here's an example of how you can do it:
@Autowired
private AdminClient adminClient;
@Autowired
private NewTopic topic;
public void createTopic() {
try {
adminClient.createTopics(Collections.singleton(topic)).all().get();
} catch (InterruptedException | ExecutionException e) {
// handle exception
}
}
This will create the topic with the specified number of partitions and replicas.
Note: The createTopics()
method is a blocking operation and may take some time to complete, depending on the size of the cluster and the number of topics being created. It is recommended to run this operation asynchronously or in a separate thread.
No comments:
Post a Comment