简体   繁体   English

如何以编程方式获取 Java 中 Kafka 主题的最新偏移量

[英]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.

相关问题 如何使用 2.x 版本的 KafkaAdminClient (Java) 获取 Kafka 主题的最新偏移量/大小 - How to get latest offset/size of a Kafka topic using KafkaAdminClient (Java) for 2.x version 如何查询 kafka 以获取主题中给定键的最新消息的最新偏移量/分区/时间戳 - How to Query kafka for latest offset / partition /timestamp for latest message for given key in a topic 如何获取 kafka 主题分区的最后/结束偏移量? - How can I get the last/end offset of a kafka topic partition? Kafka如何知道Java中为主题创建的最新分区ID - Kafka how to know the latest created partition id for a topic in Java 如何在Java中获取Kafka主题延迟 - How to get a Kafka Topic Lag in Java 如何在特定偏移量到特定偏移量中使用来自 kafka 主题的数据? - How to consume data from kafka topic in specific offset to specific offset? 如何以编程方式获取主题权限 [Kafka,Java] - How to programmatically get topics permissions [Kafka, Java] Java:当我从kafka主题开始读取时,如何从当前偏移量读取 - Java: How to read from current offset when I start reading from a kafka topic 我们如何手动重置通过 Spring Boot Java 应用程序消耗的 kafka 主题的偏移量? - How can we manually reset the offset of a kafka topic which is consumed through a spring boot java application? 如何从 Java 代码中获取 Kafka Topic 的复制因子 - How to get Replication Factor of Kafka Topic from Java code
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM