簡體   English   中英

可靠地獲取來自 Kafka 主題的最后一條(已經產生的)消息

[英]Reliably get the last (already produced) message from Kafka topic

我正在做類似下面的偽代碼

var consumer = new KafkaConsumer();
consumer.assign(topicPartitions);
var beginOff = consumer.beginningOffsets(topicPartitions);
var endOff = consumer.endOffsets(topicPartitions);
var lastOffsets = Math.max(beginOff, endOff - 1));
lastOffsets.forEach(consumer::seek);
lastMessages = consumer.poll(1 sec);
// do something with the received messages
consumer.close();

在我所做的簡單測試中,這是可行的,但我想知道是否存在一些情況,比如生產者崩潰等,偏移量不是單調遞增的? 在這種情況下,我是否必須及時返回seek() ,或者我可以從 Kafka 獲取最后一條已經生成的消息的消息偏移量?

我沒有使用事務,所以我們不需要擔心已提交的和未提交的消息。

編輯:偏移量不連續的一個例子是在日志壓縮之后。 但是,日志壓縮應始終保留最后一條消息,因為它 - 顯然 - 比所有先前的消息(相同或不同的鍵)更新。 但是理論上可以壓縮最后一條消息之前的偏移量。

Kafka 日志壓縮

kafka.apache.org/10/javadoc/中,明確提到, consumer.endOffsets

Get the last offset for the given partitions. The last offset of a partition is the offset of the upcoming message, ie the offset of the last available message + 1.

因此,當您獲得endOff - 1時,它是您獲取該主題分區時最后一個可用的 Kafka 記錄。 因此,生產者的擔憂不會因此受到影響。

還有一件事,Offset 不是由制片人決定的。 由該主題分區的分區領導者決定。 所以,它總是單調遞增的。

暫無
暫無

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

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