kafka学习:Consumer

Kafka Consumer

消费机制

new consumer / old consumer:区别offset保存的地方
Group:每个Consumer属于一个Group,可实现广播(发给所有消费组)或单播(组内负载均衡)
Rebalance:组内以Topic分区个数进行均衡,组内消费者最多有分区个数的消费者
assign模式:手动分配消费分区
subscribe模式:自动分配消费分区

  1. 消费者查询一个GroupCordinator
  2. JoinGroup,分配Partition
  3. 查找所分配Partition的Leader,进行消费

GroupCordinator职责

  • 处理JoinGroupRequest、SyncGroupRequest完成Partition分配
  • 维护_consumer_offset
  • 通过心跳检查消费者状态

GroupCordinator选择:__consumers_offsets partition# = Math.abs(groupId.hashCode() % groupMetadataTopicPartitionCount)
groupMetadataTopicPartitionCount = offsets.topic.num.partitions,默认50
该分区leader所在的broker就是被选定的coordinator

GroupRebalance触发条件

  • 新Consumer加入Group
  • Consumer 退出:主动leave、宕机、网络故障
  • Topic分区数变化(扩容)
  • Consumer调用unsubscribe

GroupRebalance流程

使用规范

  1. consumer owner线程需要确保不会异常退出,否则相当于宕机并不再发起消费请求,从而阻塞消费
  2. 确保处理完消息再做消息commit,避免拉取消息后消息处理失败(包括拉取消息后宕机),无法重新拉取未处理完成的消息
  3. consumer避免频繁加入和退出group,否则会导致频繁rebalance阻塞消费。
  4. consumer数量不能超过topic分区数,否则会有consumer闲置
  5. consumer需要周期poll维持心跳,否则也会导致频繁退出和加入,后果同3
  6. consumer拉取的消息本地缓存应限制大小避免OOM
  7. kafka不能保证消息不重复,业务侧需要保持消息处理幂等性
  8. 消费线程退出要调用consumer的close方法主动退出group,避免同组其他消费者阻塞session.timeout.ms的时间
Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

请我喝杯咖啡吧~

支付宝
微信