1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| package com.matrix.kafka;
import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties;
import kafka.consumer.Consumer; import kafka.consumer.ConsumerConfig; import kafka.consumer.ConsumerIterator; import kafka.consumer.KafkaStream; import kafka.javaapi.consumer.ConsumerConnector; import kafka.message.MessageAndMetadata;
public class ConsumerDemo {
private static final String topic = "chinesescore"; private static final Integer threads = 1;
public static void main(String[] args) { Properties props = new Properties(); props.put("zookeeper.connect", "master:2181,slave1:2181,slave2:2181"); props.put("group.id", "1111"); props.put("auto.offset.reset", "smallest");
ConsumerConfig config = new ConsumerConfig(props); ConsumerConnector consumer = Consumer.createJavaConsumerConnector(config); Map<String, Integer> topicCountMap = new HashMap<String, Integer>(); topicCountMap.put(topic, 1); Map<String, List<KafkaStream<byte[], byte[]>>> consumerMap = consumer.createMessageStreams(topicCountMap); List<KafkaStream<byte[], byte[]>> streams = consumerMap.get("chinesescore");
for (final KafkaStream<byte[], byte[]> kafkaStream : streams) { new Thread(new Runnable() { @Override public void run() { for (MessageAndMetadata<byte[], byte[]> mm : kafkaStream) { String msg = new String(mm.message()); System.out.println(msg); } }
}).start();
} } }
|