標籤:apply 指令碼 非同步 next localhost 如何 family gradle force
Kafka官方提供了兩個指令碼來管理topic,包括topic的增刪改查。其中kafka-topics.sh負責topic的建立與刪除;kafka-configs.sh指令碼負責topic的修改和查詢,但很多使用者都更加傾向於使用程式API的方式對topic進行操作。 上一篇文章中提到了如何使用用戶端協議(client protocol)來建立topic,本文則使用伺服器端的Java API對topic進行增刪改查。開始之前,需要明確的是,下面的代碼需要引入kafka-core的依賴,以kafka 0.10.2版本為例:
Maven版本
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka_2.10</artifactId>
<version>0.10.2.0</version>
</dependency>
Gradle版本
compile group: ‘org.apache.kafka‘, name: ‘kafka_2.10‘, version: ‘0.10.2.0‘
建立topic
ZkUtils zkUtils = ZkUtils.apply("localhost:2181", 30000, 30000, JaasUtils.isZkSecurityEnabled());// 建立一個單分區單副本名為t1的topicAdminUtils.createTopic(zkUtils, "t1", 1, 1, new Properties(), RackAwareMode.Enforced$.MODULE$);zkUtils.close();
刪除topic
ZkUtils zkUtils = ZkUtils.apply("localhost:2181", 30000, 30000, JaasUtils.isZkSecurityEnabled());// 刪除topic ‘t1‘AdminUtils.deleteTopic(zkUtils, "t1");zkUtils.close();
比較遺憾地是,不管是建立topic還是刪除topic,目前Kafka實現的方式都是後台非同步作業的,而且沒有提供任何回調機制或返回任何結果給使用者,所以使用者除了捕獲異常以及查詢topic狀態之外似乎並沒有特別好的辦法可以檢測操作是否成功。
查詢topic
ZkUtils zkUtils = ZkUtils.apply("localhost:2181", 30000, 30000, JaasUtils.isZkSecurityEnabled());// 擷取topic ‘test‘的topic屬性屬性Properties props = AdminUtils.fetchEntityConfig(zkUtils, ConfigType.Topic(), "test");// 查詢topic-level屬性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();
修改topic
ZkUtils zkUtils = ZkUtils.apply("localhost:2181", 30000, 30000, JaasUtils.isZkSecurityEnabled());Properties props = AdminUtils.fetchEntityConfig(zkUtils, ConfigType.Topic(), "test");// 增加topic層級屬性props.put("min.cleanable.dirty.ratio", "0.3");// 刪除topic層級屬性props.remove("max.message.bytes");// 修改topic ‘test‘的屬性AdminUtils.changeTopicConfig(zkUtils, "test", props);zkUtils.close();
Kafka Java API操作topic