kafka java串連操作

來源:互聯網
上載者:User

Java串連kafka操作,單機版kafka

代碼記錄如下

1、maven添加依賴配置:

<dependency><groupId>org.apache.kafka</groupId><artifactId>kafka_2.10</artifactId><version>0.10.2.0</version></dependency>


2、Java Code實現:

package com.sam.project.kafka;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Properties;import java.util.concurrent.TimeUnit;import org.apache.kafka.common.security.JaasUtils;import kafka.admin.AdminUtils;import kafka.admin.RackAwareMode;import kafka.consumer.Consumer;import kafka.consumer.ConsumerConfig;import kafka.consumer.ConsumerIterator;import kafka.consumer.KafkaStream;import kafka.consumer.Whitelist;import kafka.javaapi.consumer.ConsumerConnector;import kafka.message.MessageAndMetadata;import kafka.server.ConfigType;import kafka.utils.ZkUtils;import kafka.javaapi.producer.Producer;  import kafka.producer.KeyedMessage;  import kafka.producer.ProducerConfig;  import kafka.serializer.StringEncoder;  /** * Test kafka */public class App {private final static String URL = "192.168.1.114:2181";private final static String NAME = "test_topic";// 建立主題private static void createTopic() {ZkUtils zkUtils = ZkUtils.apply(URL, 30000, 30000, JaasUtils.isZkSecurityEnabled());// 建立一個單分區單副本名為t1的topicAdminUtils.createTopic(zkUtils, NAME, 1, 1, new Properties(), RackAwareMode.Enforced$.MODULE$);zkUtils.close();System.out.println("建立成功!");}// 刪除主題(未徹底刪除)private static void deleteTopic() {ZkUtils zkUtils = ZkUtils.apply(URL, 30000, 30000, JaasUtils.isZkSecurityEnabled());// 刪除topic 't1'AdminUtils.deleteTopic(zkUtils, NAME);zkUtils.close();System.out.println("刪除成功!");}// 修改主題private static void editTopic() {ZkUtils zkUtils = ZkUtils.apply(URL, 30000, 30000, JaasUtils.isZkSecurityEnabled());Properties props = AdminUtils.fetchEntityConfig(zkUtils, ConfigType.Topic(), NAME);// 增加topic層級屬性props.put("min.cleanable.dirty.ratio", "0.3");// 刪除topic層級屬性props.remove("max.message.bytes");// 修改topic 'test'的屬性AdminUtils.changeTopicConfig(zkUtils, NAME, props);zkUtils.close();}// 主題讀取private static void queryTopic() {ZkUtils zkUtils = ZkUtils.apply(URL, 30000, 30000, JaasUtils.isZkSecurityEnabled());// 擷取topic 'test'的topic屬性屬性Properties props = AdminUtils.fetchEntityConfig(zkUtils, ConfigType.Topic(), NAME);// 查詢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();}/** * @Description: 生產者 */private static void producer() {Properties properties = new Properties();     properties.put("zookeeper.connect", "192.168.1.114:2181");//聲明zk          properties.put("serializer.class", StringEncoder.class.getName());          properties.put("metadata.broker.list", "192.168.1.114:9092");// 聲明kafka broker  Producer producer = new Producer<Integer, String>(new ProducerConfig(properties)); int i=0;          while(true){              producer.send(new KeyedMessage<Integer, String>(NAME, "message: " + i++));              try {                  TimeUnit.SECONDS.sleep(1);              } catch (InterruptedException e) {                  e.printStackTrace();              }          }  }/** * @Description: 消費者 */private static void customer() {try {Properties properties = new Properties();properties.put("zookeeper.connect", URL);properties.put("auto.commit.enable", "true");properties.put("auto.commit.interval.ms", "60000");properties.put("group.id", "test_topic");ConsumerConfig consumerConfig = new ConsumerConfig(properties);ConsumerConnector javaConsumerConnector = Consumer.createJavaConsumerConnector(consumerConfig);// topic的過濾器Whitelist whitelist = new Whitelist("test_topic");List<KafkaStream<byte[], byte[]>> partitions = javaConsumerConnector.createMessageStreamsByFilter(whitelist);if (partitions == null) {System.out.println("empty!");TimeUnit.SECONDS.sleep(1);}System.out.println("partitions:"+partitions.size());// 消費訊息for (KafkaStream<byte[], byte[]> partition : partitions) {ConsumerIterator<byte[], byte[]> iterator = partition.iterator();while (iterator.hasNext()) {MessageAndMetadata<byte[], byte[]> next = iterator.next();System.out.println("partiton:" + next.partition());System.out.println("offset:" + next.offset());System.out.println("接收到message:" + new String(next.message(), "utf-8"));}}} catch (Exception e) {// TODO: handle exception}}public static void main(String[] args) { createTopic();// deleteTopic();// editTopic();// queryTopic(); //producer();//customer();}}

以上代碼實現java串連kafka主題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.