We have seen how to create, list and manage topics using Kafka console. Kafka console is good for practice and testing your code. But in production, we will need to use some API to interact with Apache Kafka. So, we will explore how to use Java and Python API with Apache Kafka. In this article, We will learn to Create and list Kafka topics in Java.

Create Kafka topics in Java

We can use ‘kafka.zk.AdminZkClient’ library to create topics and change their configuration using Java code.

First, we need to connect to the Zookeeper server and establish ZkUtils session.

Once our session is established, we can start creating our topic. We can pass the topic configuration while creating a new topic.

Once the topic configuration is fixed, we can create the topic using the following command.

After running this code, topic named ‘myTopic’ will be created with three partitions and one replication factor.

Listing topic configuration

We can get topic configuration using the following method.

Checking topic existence

We need to check if some topic is already present in Kafka server before creating it. We can use the following function to check that

Changing topic configuration

We can modify topic configuration using the following function

Listing topics

We need to create Kafka consumer to list all topics in Kafka server. Then we can use its ‘listTopic’ method to list all topics.

This will return all the topics in Kafka server.

Deleting Kafka topic

Though it is not often we need to delete Kafka topics; We can use the following method to do so.

I hope you have learned how we can manage topics in Kafka server using Java. You can find this detailed code at git repository.

In the next article, we will see how to write Kafka Producer using Java. Till then, Happy learning.

This Post Has One Comment

  1. Thanks for great post, exactly what I was looking for.

    I played around with the examples and copy pasted the examples. I observe the following strange behavior. Namely, the topic rention.bytes gets set to a value, and then after line zookeeperClient.close(); (which I added) the old property value appears again. Mahesh, any ideas why this happens?

Leave a Reply

Close Panel