kafka的Java用戶端範例程式碼(kafka_2.11-0.8.2.2)

來源:互聯網
上載者:User

標籤:iter   new   second   zookeeper   indexof   message   this   tin   pac   

使用Producer,ConsumerConnector

HelloWorldProducer.java

package cn.ljh.kafka.kafka_helloworld;import java.util.Date;import java.util.Properties;import java.util.Random;import kafka.javaapi.producer.Producer;import kafka.producer.KeyedMessage;import kafka.producer.ProducerConfig;public class HelloWorldProducer {    public static void main(String[] args) {        long events = Long.parseLong(args[0]);        Random rnd = new Random();         Properties props = new Properties();        //配置kafka叢集的broker地址,建議配置兩個以上,以免其中一個失效,但不需要配全,叢集會自動尋找leader節點。        props.put("metadata.broker.list", "192.168.137.176:9092,192.168.137.176:9093");        //配置value的序列化類別        //key的序列化類別key.serializer.class可以單獨配置,預設使用value的序列化類別        props.put("serializer.class", "kafka.serializer.StringEncoder");        //配置partitionner選擇策略,可選配置        props.put("partitioner.class", "cn.ljh.kafka.kafka_helloworld.SimplePartitioner");        props.put("request.required.acks", "1");         ProducerConfig config = new ProducerConfig(props);         Producer<String, String> producer = new Producer<String, String>(config);         for (long nEvents = 0; nEvents < events; nEvents++) {                long runtime = new Date().getTime();                 String ip = "192.168.2." + rnd.nextInt(255);                String msg = runtime + ",www.example.com," + ip;                KeyedMessage<String, String> data = new KeyedMessage<String, String>("page_visits", ip, msg);               producer.send(data);        }        producer.close();    }}

SimplePartitioner.java

package cn.ljh.kafka.kafka_helloworld;import kafka.producer.Partitioner;import kafka.utils.VerifiableProperties; public class SimplePartitioner implements Partitioner {    public SimplePartitioner (VerifiableProperties props) {     }     public int partition(Object key, int a_numPartitions) {        int partition = 0;        String stringKey = (String) key;        int offset = stringKey.lastIndexOf(‘.‘);        if (offset > 0) {           partition = Integer.parseInt( stringKey.substring(offset+1)) % a_numPartitions;        }       return partition;  } }

ConsumerGroupExample.java

package cn.ljh.kafka.kafka_helloworld;import kafka.consumer.ConsumerConfig;import kafka.consumer.KafkaStream;import kafka.javaapi.consumer.ConsumerConnector; import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Properties;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit; public class ConsumerGroupExample {    private final ConsumerConnector consumer;    private final String topic;    private  ExecutorService executor;     public ConsumerGroupExample(String a_zookeeper, String a_groupId, String a_topic) {        consumer = kafka.consumer.Consumer.createJavaConsumerConnector(                createConsumerConfig(a_zookeeper, a_groupId));        this.topic = a_topic;    }     public void shutdown() {        if (consumer != null) consumer.shutdown();        if (executor != null) executor.shutdown();        try {            if (!executor.awaitTermination(5000, TimeUnit.MILLISECONDS)) {                System.out.println("Timed out waiting for consumer threads to shut down, exiting uncleanly");            }        } catch (InterruptedException e) {            System.out.println("Interrupted during shutdown, exiting uncleanly");        }   }     public void run(int a_numThreads) {        Map<String, Integer> topicCountMap = new HashMap<String, Integer>();        topicCountMap.put(topic, new Integer(a_numThreads));        Map<String, List<KafkaStream<byte[], byte[]>>> consumerMap = consumer.createMessageStreams(topicCountMap);        List<KafkaStream<byte[], byte[]>> streams = consumerMap.get(topic);         // now launch all the threads        //        executor = Executors.newFixedThreadPool(a_numThreads);         // now create an object to consume the messages        //        int threadNumber = 0;        for (final KafkaStream stream : streams) {            executor.submit(new ConsumerTest(stream, threadNumber));            threadNumber++;        }    }     private static ConsumerConfig createConsumerConfig(String a_zookeeper, String a_groupId) {        Properties props = new Properties();        props.put("zookeeper.connect", a_zookeeper);        props.put("group.id", a_groupId);        props.put("zookeeper.session.timeout.ms", "400");        props.put("zookeeper.sync.time.ms", "200");        props.put("auto.commit.interval.ms", "1000");         return new ConsumerConfig(props);    }     public static void main(String[] args) {//        String zooKeeper = args[0];//        String groupId = args[1];//        String topic = args[2];//        int threads = Integer.parseInt(args[3]);                String zooKeeper = "192.168.137.176:2181,192.168.137.176:2182,192.168.137.176:2183";        String groupId = "group1";        String topic = "page_visits";        int threads = 5;         ConsumerGroupExample example = new ConsumerGroupExample(zooKeeper, groupId, topic);        example.run(threads);         try {            Thread.sleep(10000);        } catch (InterruptedException ie) {         }        example.shutdown();    }}

ConsumerTest.java

package cn.ljh.kafka.kafka_helloworld;import kafka.consumer.ConsumerIterator;import kafka.consumer.KafkaStream; public class ConsumerTest implements Runnable {    private KafkaStream m_stream;    private int m_threadNumber;     public ConsumerTest(KafkaStream a_stream, int a_threadNumber) {        m_threadNumber = a_threadNumber;        m_stream = a_stream;    }     public void run() {        ConsumerIterator<byte[], byte[]> it = m_stream.iterator();        //線程會一直等待有訊息進入        while (it.hasNext())            System.out.println("Thread " + m_threadNumber + ": " + new String(it.next().message()));        System.out.println("Shutting down Thread: " + m_threadNumber);    }}

kafka的Java用戶端範例程式碼(kafka_2.11-0.8.2.2)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.