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.
String zookeeperHost = "127.0.0.1:2181"; Boolean isSucre = false; int sessionTimeoutMs = 200000; int connectionTimeoutMs = 15000; int maxInFlightRequests = 10; Time time = Time.SYSTEM; String metricGroup = "myGroup"; String metricType = "myType"; KafkaZkClient zkClient = KafkaZkClient.apply(zookeeperHost,isSucre,sessionTimeoutMs, connectionTimeoutMs,maxInFlightRequests,time,metricGroup,metricType); AdminZkClient adminZkClient = new AdminZkClient(zkClient);
Once our session is established, we can start creating our topic. We can pass the topic configuration while creating a new topic.
String topicName1 = "myTopic"; int partitions = 3; int replication = 1; // you should have replication factor less than or equal to number of nodes in Kafka cluster Properties topicConfig = new Properties(); // you can pass topic configurations while creating 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
We need to create Kafka consumer to list all topics in Kafka server. Then we can use its ‘listTopic’ method to list all topics.
Seq allTopic = zkClient.getAllTopicsInCluster(); System.out.println("Cluset has " + allTopic.length() + " topics"); System.out.println(allTopic);
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.