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

作者石臻臻, CSDN博客之星Top5Kafka Contributornacos Contributor华为云 MVP ,腾讯云TVP, 滴滴Kafka技术专家 KnowStreaming PMC)


Know Streaming 是滴滴开源的Kafka运维管控平台, 有兴趣一起参与参与开发的同学,但是怕自己能力不够的同学,可以联系我,带你一起你参与开源!
KnowStreaming 体验环境请访问:https://demo.knowstreaming.com/

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

在这里插入图片描述

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

问题

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数据进行消费的时候,会先去判断是否需要进行重平衡。

判断条件是:如果订阅的Topic元信息有变更,或者订阅的Topic有增删,都需要进行重平衡之后再去Poll数据。

而分区副本重分配和 扩分区 因为属于变更了订阅的Topic元信息, 则需要重平衡

猜你喜欢

转载自blog.csdn.net/u010634066/article/details/127509011