Kafka officially provided two scripts to manage the topic, including additions and deletions to topic. Where kafka-topics.sh is responsible for the creation and deletion of topic, kafka-configs.sh script is responsible for topic modification and query, but many users are more inclined to use the program API to operate topic. The previous article mentioned how to use the client protocol to create a topic, and this article uses the server-side Java API to make topic. before you begin, it is clear that the following code needs to introduce Kafka-core dependencies to Kafka 0.10.2 For example:
maven version
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka_2.10</artifactId>
<version>0.10.2.0</version>
</dependency>
Gradle version
compile group: ' Org.apache.kafka ', Name: ' kafka_2.10 ', version: ' 0.10.2.0 '
Create topic
Zkutils zkutils = zkutils.apply ("localhost:2181", 30000, 30000, jaasutils.iszksecurityenabled ()); // Create a single-partition topic with a single copy called T1 New Properties (), rackawaremode.enforced$. module$); Zkutils.close ();
Delete Topic
Zkutils zkutils = zkutils.apply ("localhost:2181", 30000, 30000, jaasutils.iszksecurityenabled ()); // Delete topic ' T1 ' Adminutils.deletetopic (zkutils, "T1"); Zkutils.close ();
Unfortunately, whether you create topic or delete topic, the current Kafka implementation is in the background asynchronous operation, and does not provide any callback mechanism or return any results to the user, So the user does not seem to have a particularly good way to detect whether the operation was successful in addition to catching exceptions and querying the topic state.
query topic
zkutils zkutils = zkutils.apply ("localhost:2181", 30000, 30000 // Get the Topic Property property of topic ' Test ' Properties props = Adminutils.fetchentityconfig (Zkutils, Configtype.topic (), "Test" // query Topic-level property Iterator it = Props.entryset (). Iterator (); while (It.hasnext ()) {map.entry Entry = (Map.entry) It.next (); Object key = Entry.getkey (); Object value = Entry.getvalue (); System.out.println (key + "=" + value);} Zkutils.close ();
Modify Topic
Zkutils zkutils = zkutils.apply ("localhost:2181", 30000, 30000= Adminutils.fetchentityconfig (ZkUtils, Configtype.topic (), "Test"); // Add topic level attribute props.put ("Min.cleanable.dirty.ratio", "0.3"); // Delete Topic level attribute props.remove ("Max.message.bytes"); // Modify the properties of the topic ' Test ' Adminutils.changetopicconfig (zkutils, "test", props); Zkutils.close ();
Kafka Java API Operation Topic