作者:石臻臻,
最近有個靓仔問我, 擴分區之後 消費組會不會重新平衡呢?
那我們今天從源碼的角度來一起分析一下, 擴分區能否重平衡?
問題
Kafka擴分區 或者 分區副本重配置設定之後 是否會自動重新平衡?
源碼探究
ConsumerCoordinator#rejoinNeededOrPending
@Override
public boolean rejoinNeededOrPending() {
if (!subscriptions.hasAutoAssignedPartitions())
return false;
// we need to rejoin if we performed the assignment and metadata has changed;
// also for those owned-but-no-longer-existed partitions we should drop them as lost
// 如果訂閱的Topic元資訊有過變更,則需要重新發起joinGroup請求
if (assignmentSnapshot != null && !assignmentSnapshot.matches(metadataSnapshot)) {
log.info("Requesting to re-join the group and trigger rebalance since the assignment metadata has changed from {} to {}",
assignmentSnapshot, metadataSnapshot);
requestRejoin();
return true;
}
// we need to join if our subscription has changed since the last join
//如果我們的訂閱自上次加入以來發生了變化,我們需要重新發起請求 JoinGroup
if (joinedSubscription != null && !joinedSubscription.equals(subscriptions.subscription())) {
log.info("Requesting to re-join the group and trigger rebalance since the subscription has changed from {} to {}",
joinedSubscription, subscriptions.subscription());
requestRejoin();
return true;
}
return super.rejoinNeededOrPending();
}
這段代碼就是用于判斷是否能夠重新發起JoinGroup請求的邏輯。
主要有以下兩點:
- 如果訂閱的Topic元資訊有過變更,則需要重新發起joinGroup請求
- 如果我們的訂閱自上次加入以來發生了變化,我們需要重新發起請求 JoinGroup
是以很好了解
- 如果我們擴分區了或者分區副本重配置設定了, 那麼就屬于Topic的元資訊有過變更了。這裡的判定邏輯及時True。需要重平衡
- 如果我們訂閱的Topic有變更(新增删除)了,那麼也需要重平衡
當然這個接口觸發時機是 KafkaConsumer.poll
結論
消費者用戶端在Poll資料進行消費的時候,會先去判斷是否需要進行重平衡。