这是我的消费者代码:
System.out.println("1/2+1/2="+ (1/2+1/2));
启动服务器:
public class KafkaConsumer {
private ConsumerConnector consumerConnector = null;
private final String topic = "JsonTopic";
public void initialize() {
Properties props = new Properties();
props.put("zookeeper.connect", "localhost:2181");
props.put("group.id", "testgroup");
props.put("kafka.topic", "JsonTopic");
props.put("zookeeper.session.timeout.ms", "400");
props.put("zookeeper.sync.time.ms", "300");
props.put("auto.commit.interval.ms", "1000");
ConsumerConfig conConfig = new ConsumerConfig(props);
consumerConnector = Consumer.createJavaConsumerConnector(conConfig);
}
public void consume() throws IOException {
Map<String, Integer> topicCount = new HashMap<String, Integer>();
topicCount.put(topic, new Integer(1));
//ConsumerConnector creates the message stream for each topic
Map<String, List<KafkaStream<byte[], byte[]>>> consumerStreams =consumerConnector.createMessageStreams(topicCount);
List<KafkaStream<byte[], byte[]>> kStreamList = consumerStreams.get(topic);
for (final KafkaStream<byte[], byte[]> kStreams : kStreamList) {
ConsumerIterator<byte[], byte[]> consumerItem = kStreams.iterator();
while (consumerItem.hasNext())
{
System.out.println("Message consumed from topic[" + topic + "] : " + new String(consumerItem.next().message()));
// writeToFile(new String(consumerItem.next().message()),"/root/abc.txt");
}
}
//Shutdown the consumer connector
if (consumerConnector != null)
consumerConnector.shutdown();
}
启动产品:
./kafka-server-start.sh /usr/hdp/2.3.0.0-2557/etc/kafka/conf.default/server.properties
我在控制台中没有得到任何输出。
[root@sandbox bin]# ./kafka-console-producer.sh --broker-list localhost:9092 --topic JsonTopic
HI
Hello
答案 0 :(得分:1)
默认情况下,启动消费者时,会忽略Kafka主题中的所有现有数据,并且只会消耗消费者启动后出现的新消息。根据您对事件顺序的描述,您启动了控制台生成器,编写消息然后启动Kafka使用者。因此,不会收到任何消息。消费者启动后,您可以尝试发送一些消息。或者,您可以通过将auto.offset.reset设置为&#34;最早&#34;来配置消费者。适用于0.9和#34;最小的&#34;对于老消费者。这将选择确保消费者在启动之前获取Kafka主题中已有的消息。