起因:
某天,項目組收到大量的kafka消息積壓告警。查看了kafka日志后,發現 kafka不斷地 rebalance(再均衡)。
Rebalance (再均衡):
分區的所有權從一個消費者轉移到另一個消費者,這樣的行為被稱為Rebalance (再均衡).
在再均衡期間,消費者無法消費消息,造成整個群組一小段時間的不可用。
Rebalance 的觸發條件:
-
當 Consumer Group 組成員數量發生變化
(1)新成員加入
(2)組成員主動離開(3)組成員崩潰
- 消費者心跳超時,導致 rebalance。
- 消費者處理時間過長,導致 rebalance。
-
當訂閱主題數量發生變化
-
當訂閱主題的分區數發生變化
日志:
[2023-12-11 xx:xx:xx] INFO [GroupCoordinator 1]: Member consumer-anonymous. in group anonymous. has failed, removing it from the group (kafka.coordinator.group.GroupCoordinator)
[2023-12-11 xx:xx:xx] INFO [GroupCoordinator 1]: Preparing to rebalance group anonymous. in state PreparingRebalance with old generation 1 (__consumer_offsets-5) (reason: removing member consumer-anonymous. on heartbeat expiration) (kafka.coordinator.group.GroupCoordinator)
[2023-12-11 xx:xx:xx] INFO [GroupCoordinator 1]: Group anonymous. with generation 2 is now empty (__consumer_offsets-5) (kafka.coordinator.group.GroupCoordinator)
[2023-12-11 xx:xx:xx] WARN Attempting to send response via channel for which there is no open connection, connection id :9092 (kafka.network.Processor)
原因:
kafka消費消息后,如果業務邏輯處理時間過長,會導致消費線程與 Coordinator(協調器) 的 heartbeat (心跳) 超時,Coordinator 判斷 Consumer 已經宕機,就將 Consumer 從消費組中剔除,并觸發了 Rebalance 機制 。
解決:
優先解決生產問題:先調整參數,避免頻繁 Rebalance。
如果想從根本上解決,還需要優化消費邏輯,提高性能,快速消費完,避免超時。
session.timeout.ms : 心跳超時時間
heartbeat.interval.ms : 心跳時間間隔
max.poll.interval.ms : 每次消費的處理時間
max.poll.records : 每次消費的消息數
-
session.timeout.ms: 心跳超時時間,默認 10s。當心跳超時時間超過 session.timeout.ms ,會認為 Consumer 已退出 ,將 Consumer 從消費組中剔除,觸發 Rebalance 機制。可以適當調大 session.timeout.ms,避免頻繁 Rebalance 。
-
heartbeat.interval.ms : 這個是心跳時間間隔,默認值是:3s。 該值必須小于 session.timeout.ms,否則會超時。
-
max.poll.interval.ms :如果消費端在該間隔內沒有發起 poll 操作,該消費者將被剔除,觸發重平衡,將該消費者分配的隊列分配給其他消費者。默認為 5 分鐘。
-
max.poll.records: 每次消費的時候,獲取多少條消息。默認值為 500。
獲取的消息條數越多,需要處理的時間越長。所以每次拉取的消息數不能太多,需要保證在 max.poll.interval.ms 設置的時間內能消費完,否則會發生 rebalance。可以適當調小 max.poll.records,避免頻繁 Rebalance 。
參考資料:
https://blog.csdn.net/riemann_/article/details/122484531
https://blog.csdn.net/penriver/article/details/121556161