Kafka通讯代码03

  • Producer
  • Consumer
  • GroupConsumer

1、MqConsumerGroup.java

package com.neohope.kafka.test;

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 MqConsumerGroup {
    private final ConsumerConnector consumer;
    private final String topic;
    private  ExecutorService executor;
    private ConsumerThread[] m_Threads;

    public MqConsumerGroup(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) throws InterruptedException {
        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
        //
        m_Threads = new ConsumerThread[a_numThreads];
        int threadNumber = 0;
        for (final KafkaStream stream : streams) {
            m_Threads[threadNumber] = new ConsumerThread(stream, threadNumber);
            executor.submit(m_Threads[threadNumber]);
            threadNumber++;
        }
    }

    public void WaitForEnd(int a_numThreads) throws InterruptedException {
        boolean bEnd =false;

        while(!bEnd) {
            Thread.sleep(200);
            for (int threadNumber = 0; threadNumber < a_numThreads; threadNumber++) {
                if (m_Threads[threadNumber].m_end)
                {
                    bEnd = true;
                }
            }
        }
    }

    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) throws InterruptedException {
        String zooKeeper = "localhost:2181";
        String groupId = "group1";
        String topic = "neoTopic";
        int threads = 2;

        MqConsumerGroup mqcGroup = new MqConsumerGroup(zooKeeper, groupId, topic);
        mqcGroup.run(threads);
        mqcGroup.WaitForEnd(threads);
        mqcGroup.shutdown();
    }
}

2、ConsumerThread.java

package com.neohope.kafka.test;

import kafka.consumer.ConsumerIterator;
import kafka.consumer.KafkaStream;
import kafka.message.MessageAndMetadata;

public class ConsumerThread implements Runnable {
    private KafkaStream m_stream;
    private int m_threadNumber;
    public Boolean m_end = false;

    public ConsumerThread(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!=null && it.hasNext()) {
            MessageAndMetadata<byte[], byte[]> msg = it.next();
            String key = new String(msg.key());
            String value = new String(msg.message());
            System.out.println("Thread " + m_threadNumber +  " Key: " + key +  " Value: "+ value);
            if(key.equals("-=END=-"))
            {
                m_end = true;
            }
        }

        System.out.println("Shutting down Thread: " + m_threadNumber);
    }
}

3、测试

#开启zookeeper
bin\windows\zookeeper-server-start.bat config\zookeeper.properties
#开启kafka-server
bin\windows\kafka-server-start.bat config\server.properties
#运行MqProducer.Main
#运行MqConsumerGroup.Main即可

Leave a Reply

Your email address will not be published. Required fields are marked *

*