[英]How to programmatically get latest offset of a Kafka topic in Java
Here is what I am trying这是我正在尝试的
Collection <TopicPartition> partitions = consumer.partitionsFor(topic).stream();
And also how to indicate you've hit the end or there isn't anymore messages to consume.以及如何表明您已经结束或不再有消息可供使用。 If the offset doesn't match the broker's end offset at the time how to do that.如果偏移量与当时经纪人的结束偏移量不匹配怎么办。
Any suggestions.有什么建议么。
In order to get the latest offset you can either use the command line:为了获得最新的偏移量,您可以使用命令行:
./bin/kafka-run-class.sh kafka.tools.GetOffsetShell \
--broker-list localhost:9092 \
--topic topicName
or programmatically in Java:或以编程方式在 Java 中:
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(consumerProperties)) {
consumer.subscribe(Arrays.asList("topicName"));
Set<TopicPartition> assignment;
while ((assignment = consumer.assignment()).isEmpty()) {
consumer.poll(Duration.ofMillis(500));
}
consumer.endOffsets(assignment).forEach((partition, offset) -> System.out.println(partition + ": " + offset));
}
Now if you want to force the consumer to start consuming from the latest offset, you can either use the following property:现在,如果您想强制消费者从最新的偏移量开始消费,您可以使用以下属性:
props.put("auto.offset.reset", "latest");
// or props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest");
or force it to consume from latest offset using或强制它从最新的偏移量使用
consumer.seekToEnd();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.