Kafka Java API操作topic

來源:互聯網
上載者:User

標籤: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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.