簡體   English   中英

如何以編程方式獲取 Java 中 Kafka 主題的最新偏移量

[英]How to programmatically get latest offset of a Kafka topic in Java

這是我正在嘗試的

Collection <TopicPartition> partitions = consumer.partitionsFor(topic).stream();

以及如何表明您已經結束或不再有消息可供使用。 如果偏移量與當時經紀人的結束偏移量不匹配怎么辦。

有什么建議么。

為了獲得最新的偏移量,您可以使用命令行:

./bin/kafka-run-class.sh kafka.tools.GetOffsetShell \
    --broker-list localhost:9092 \
    --topic topicName

或以編程方式在 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));
}

現在,如果您想強制消費者從最新的偏移量開始消費,您可以使用以下屬性:

props.put("auto.offset.reset", "latest"); 
// or props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest");

或強制它從最新的偏移量使用

consumer.seekToEnd();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM