在消费者订阅主题并开始消费消息时,它从头开始读取消息是否有任何方法只读取未读消息?这是我用来消费消息的代码。
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("group.id", "test");
props.put("enable.auto.commit", "true");
props.put("auto.commit.interval.ms", "1000");
props.put("session.timeout.ms", "30000");
props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.put("value.deserializer","org.apache.kafka.common.serialization.StringDeserializer");
KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(props);
//Kafka Consumer subscribes list of topics here.
consumer.subscribe(Arrays.asList(topicName));
while (true) {
ConsumerRecords<String, String> records = consumer.poll(100);
for (ConsumerRecord<String, String> record : records)
System.out.printf("offset = %d, key = %s, value= %s\n", record.offset(), record.key(), record.value());
}
答案 0 :(得分:3)
关闭auto.commit并在应用成功读取后手动提交每个消息偏移量。这样,如果应用程序崩溃,它将在最后一次提交的偏移量处重新启动。
答案 1 :(得分:0)
我试过你的代码,它只读取未读的消息。什么是您的客户端版本和服务器版本?