天天看点

Kafka扩分区和分区副本重分配之后消费组会自动均衡吗?

作者:石臻臻,

最近有个靓仔问我, 扩分区之后 消费组会不会重新平衡呢?

Kafka扩分区和分区副本重分配之后消费组会自动均衡吗?

那我们今天从源码的角度来一起分析一下, 扩分区能否重平衡?

问题

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请求的逻辑。

主要有以下两点:

  1. 如果订阅的Topic元信息有过变更,则需要重新发起joinGroup请求
  2. 如果我们的订阅自上次加入以来发生了变化,我们需要重新发起请求 JoinGroup

所以很好理解

  • 如果我们扩分区了或者分区副本重分配了, 那么就属于Topic的元信息有过变更了。这里的判定逻辑及时True。需要重平衡
  • 如果我们订阅的Topic有变更(新增删除)了,那么也需要重平衡

当然这个接口触发时机是 KafkaConsumer.poll

结论

消费者客户端在Poll数据进行消费的时候,会先去判断是否需要进行重平衡。