I want to create a topic in Kafka (kafka_2.8.0-0.8.1.1) through java. It is working fine if I create a topic in command prompt, and If I push message through java api. But I want to create a topic through java api. After a long search I found below code,
ZkClient zkClient = new ZkClient("localhost:2181", 10000, 10000);
AdminUtils.createTopic(zkClient, myTopic, 10, 1, new Properties());
I tried above code and it is showing that topic is created but I am not able to push message in the topic. Any thing wrong in my code? Or any other way to achieve the above?
The process seems to be pretty much simplified in API 0.11.0+. Using that, it can be done as follows
The contents of
kafka.properties
file are as followsNote that the instance of the AdminClient must be closed in order to reflect the newly created topic.
Just a pointer to anyone looking at this with a updated version of Kafka (At the time of writing this, I was using Kafka v0.10.0.0).
You have to change;
To the following;
It is also a good idea to close the connection once finished;
Original answer
I fixed it.. After a long research..
From the above code, ZkClient will create a topic but this topic information will not have awareness for the kafka. So what we have to do is, we need to create object for ZkClient in following way,
First import the below statement,
and create object for ZkClient in the following way,
Edit 1: (for @ajkret comment)
For those trying to achieve this in kafka v0.10.2.1 and running into issues with serialization error '
java.io.StreamCorruptedException: invalid stream header: 3139322E
' following is a sample working code with the needful imports.AdminUtils API is getting deprecated. There is new API AdminZkClient which we can use to manage topics in Kafka server.
You can refer this link for details: https://www.analyticshut.com/streaming-services/kafka/create-and-list-kafka-topics-in-java/