03. Kafka 消费者组与偏移量管理

Kafka 消费者: Consumer Group 机制、Rebalance、自动/手动提交偏移量

1. 消费者组

Topic: orders (3 partitions)

Consumer Group: order-processors
  Consumer 1 → Partition 0
  Consumer 2 → Partition 1
  Consumer 3 → Partition 2

新增 Consumer 4 → Rebalance → 可能:
  Consumer 1 → Partition 0
  Consumer 2 → Partition 1
  Consumer 3 → Partition 2
  Consumer 4 → (空闲,无 partition 分配)

分区数 ≥ 消费者数,才能充分利用

2. 偏移量提交策略

// 自动提交(默认)
props.put("enable.auto.commit", true);
props.put("auto.commit.interval.ms", 5000);

// 手动提交(推荐,精确控制)
props.put("enable.auto.commit", false);

consumer.subscribe(Arrays.asList("orders"));
while (true) {
    ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));
    for (ConsumerRecord<String, String> record : records) {
        process(record);
    }
    consumer.commitSync();  // 处理完一批再提交
}

3. Rebalance

触发条件:

  • 新消费者加入组
  • 消费者离开组
  • Topic 分区变化

再均衡策略(partition.assignment.strategy):

  • Range(默认):按 Topic 范围分配
  • RoundRobin:轮询所有分区
  • Sticky:尽量保持分配不变
  • CooperativeSticky:渐进式再均衡,不停消费(推荐)

延伸阅读

继续阅读

探索更多技术文章

浏览归档,发现更多关于系统设计、工具链和工程实践的内容。

全部文章 返回首页

「kafka」更多文章

  1. 事件驱动架构:Event Sourcing、CQRS 与 Saga 模式
  2. Kafka 运维监控与故障恢复:JMX 指标、Lag 监控与分区重分配
  3. Kafka 详解:分布式日志系统、ISR 与一致性保证