kafka多线程消费

kafka多线程消费

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import kafka.consumer.ConsumerIterator;
import kafka.consumer.KafkaStream;
import kafka.javaapi.consumer.ConsumerConnector;
import net.sf.json.JSONArray;

public class MessagePop {

    private String topic;
    private int numThreads = 3;
    public  ConsumerConnector consumer;
    private ExecutorService executor;
    private BlockingQueue _message = new LinkedBlockingQueue();
    
    public JSONArray getMessage(){
        JSONArray msg = null;
        if (!_message.isEmpty()) {
            msg = JSONArray.fromObject(_message.poll());
        }  
        return msg;
    }
    
    public void setTopic(String Topic){
        topic = Topic;
    }
    @SuppressWarnings("unchecked")
    public void run() {
        Map topicCountMap = new HashMap();
        topicCountMap.put(topic, new Integer(numThreads));
        Map>> consumerMap = consumer.createMessageStreams(topicCountMap);
        List> streams = consumerMap.get(topic);
        executor = Executors.newFixedThreadPool(numThreads);
        for (@SuppressWarnings("rawtypes")
        final KafkaStream stream : streams) {
            executor.submit(new ConsumerRunnable(stream, numThreads));
        }
    }  
    
    /**
     * 启用多线程读取数据,并写入到内存队列中
     */
    class ConsumerRunnable implements Runnable {
        private KafkaStream m_stream;

        public ConsumerRunnable(KafkaStream a_stream,
                int a_threadNumber) {
            this.m_stream = a_stream;  
        }
        
        public void run() {
            ConsumerIterator it = m_stream.iterator();
            while (it.hasNext()) {
                _message.add(new String(it.next().message()));
            }  
        }
 
    }
}


你可能感兴趣的:(kafka)