剑道第一仙

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

kafka如何手动异步提交offset

转:https://blog.csdn.net/CREATE_17/article/details/108722808

kafka手动异步提交 offset 的步骤大概分为以下几步,如下图所示:

 

 

1、配置手动提交

enable.auto.commit 修改为 false 。

2、订阅 topic

consumer.subscribe(Arrays.asList("topic name"));

3、获取 topic 各分区当前读取到的最后一条记录的offset
首先定义一个全局变量:

//用来记录当前消费的偏移
private static Map<TopicPartition, Long> offsets = new HashMap<>();
for (TopicPartition partition : records.partitions()) {
List<ConsumerRecord<String, String>> partitionRecords = records.records(partition);
// 获取当前读取到的最后一条记录的offset
long lastOffset = partitionRecords.get(partitionRecords.size() - 1).offset();
// 提交offset
offsets.put(partition, lastOffset + 1);
}
至于为什么消费者提交 offsets 时要 +1,在《Kafka消费者 之 如何提交消息的偏移量》中的概述章节里面也给出了答案。

4、手动异步提交 offset
首先定义一个全局变量:

//用来记录当需要提交的偏移
private static Map<TopicPartition, OffsetAndMetadata> commitOffset = new HashMap<>();
//
for (Map.Entry<TopicPartition, Long> entry : offsets.entrySet()) {
commitOffset.put(entry.getKey(), new OffsetAndMetadata(offsets.get(entry.getKey())));
logger.info("partition[{}], 当前待提交kafka偏移:[{}]", entry.getKey().partition(), offsets.get(entry.getKey()));
}
// 异步提交offset
consumer.commitAsync(commitOffset, (offsets, exception) -> {
if (exception != null) {
logger.error("fail to commit offsets {}, {}", offsets, exception);
// 同步提交,来做offset提交最后的保证。
consumer.commitSync();
}
});
清空:

commitOffset.clear();
offsets.clear();

 

posted on   剑道第一仙  阅读(546)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示