RocketMQ源码解析之Consumer启动

岳亮
2023-12-01

阅读须知

  • 文章中使用/* */注释的方法会做深入分析

正文

Consumer 的启动流程和 Producer 的启动流程有很多复用的部分,前面我们已经分析过 Producer 的启动流程,复用部分这里不再重复。

使用 RocketMQ Consumer 消费消息的简单配置如下,:

<bean id="rocketmqConsumer" class="org.apache.rocketmq.client.consumer.DefaultMQPushConsumer" init-method="start"
      destroy-method="shutdown">
    <property name="consumerGroup" value="${rocketmq.consumer.group}"/>
    <property name="namesrvAddr" value="${rocketmq.nameserver.address}"/>
    <property name="messageListener" ref="orderMessageListener"/>
    <property name="subscription">
        <map>
            <entry key="${rocketmq.topic}" value="*"/>
        </map>
    </property>
</bean>

我们看到配置中 init-method 配置了 start 方法,所以在 bean 的初始化过程中会调用 DefaultMQPushConsumer 的 start 方法:

public void start() throws MQClientException {
    setConsumerGroup(NamespaceUtil.wrapNamespace(this.getNamespace(), this.consumerGroup));
    /* 启动 */
    this.defaultMQPushConsumerImpl.start();
    if (null != traceDispatcher) {
        try {
            traceDispatcher.start(this.getNamesrvAddr(), this.getAccessChannel());
        } catch (MQClientException e) {
            log.warn("trace dispatcher start failed ", e);
        }
    }
}

DefaultMQPushConsumerImpl:

public synchronized void start() throws MQClientException {
    switch (this.serviceState) {
        case CREATE_JUST:
            log.info("the consumer [{}] start beginning. messageModel={}, isUnitMode={}", this.defaultMQPushConsumer.getConsumerGroup(),
                this.defaultMQPushConsumer.getMessageModel(), this.defaultMQPushConsumer.isUnitMode());
            this.serviceState = ServiceState.START_FAILED;
            // 一些配置的正确性校验
            this.checkConfig();
            // 复制订阅信息,复制消息监听器
            this.copySubscription();
            // 默认为集群模式
            if (this.defaultMQPushConsumer.getMessageModel() == MessageModel.CLUSTERING) {
                this.defaultMQPushConsumer.changeInstanceNameToPID();
            }
            // 获取并创建 client,与 Producer 启动复用同样的方法
            this.mQClientFactory = MQClientManager.getInstance().getAndCreateMQClientInstance(this.defaultMQPushConsumer, this.rpcHook);
            this.rebalanceImpl.setConsumerGroup(this.defaultMQPushConsumer.getConsumerGroup());
            this.rebalanceImpl.setMessageModel(this.defaultMQPushConsumer.getMessageModel());
            this.rebalanceImpl.setAllocateMessageQueueStrategy(this.defaultMQPushConsumer.getAllocateMessageQueueStrategy());
            this.rebalanceImpl.setmQClientFactory(this.mQClientFactory);
            this.pullAPIWrapper = new PullAPIWrapper(
                mQClientFactory,
                this.defaultMQPushConsumer.getConsumerGroup(), isUnitMode());
            this.pullAPIWrapper.registerFilterMessageHook(filterMessageHookList);
            if (this.defaultMQPushConsumer.getOffsetStore() != null) {
                this.offsetStore = this.defaultMQPushConsumer.getOffsetStore();
            } else {
                // 根据不同的消息模式创建不同的偏移量存储服务
                switch (this.defaultMQPushConsumer.getMessageModel()) {
                    case BROADCASTING:
                        this.offsetStore = new LocalFileOffsetStore(this.mQClientFactory, this.defaultMQPushConsumer.getConsumerGroup());
                        break;
                    case CLUSTERING:
                        this.offsetStore = new RemoteBrokerOffsetStore(this.mQClientFactory, this.defaultMQPushConsumer.getConsumerGroup());
                        break;
                    default:
                        break;
                }
                this.defaultMQPushConsumer.setOffsetStore(this.offsetStore);
            }
            this.offsetStore.load();
            // 判断消息监听器是顺序消息|并发消息(普通消息)来创建对应的消息消费服务
            if (this.getMessageListenerInner() instanceof MessageListenerOrderly) {
                this.consumeOrderly = true;
                this.consumeMessageService =
                    new ConsumeMessageOrderlyService(this, (MessageListenerOrderly) this.getMessageListenerInner());
            } else if (this.getMessageListenerInner() instanceof MessageListenerConcurrently) {
                this.consumeOrderly = false;
                this.consumeMessageService =
                    new ConsumeMessageConcurrentlyService(this, (MessageListenerConcurrently) this.getMessageListenerInner());
            }
            // 消费服务启动,对于并发消息消费服务,会启动定时清理垃圾消息服务;顺序消息我们单独分析
            this.consumeMessageService.start();
            // 添加 consumerGroup 和消费者实例的映射
            boolean registerOK = mQClientFactory.registerConsumer(this.defaultMQPushConsumer.getConsumerGroup(), this);
            if (!registerOK) {
                this.serviceState = ServiceState.CREATE_JUST;
                // 添加映射失败停止消费服务,失败的原因可能为同一个 consumerGroup 被多次添加,这是不允许的
                this.consumeMessageService.shutdown();
                throw new MQClientException("The consumer group[" + this.defaultMQPushConsumer.getConsumerGroup()
                    + "] has been created before, specify another name please." + FAQUrl.suggestTodo(FAQUrl.GROUP_NAME_DUPLICATE_URL),
                    null);
            }
            // 启动客户端实例,和 Producer 启动复用相同的流程
            mQClientFactory.start();
            log.info("the consumer [{}] start OK.", this.defaultMQPushConsumer.getConsumerGroup());
            // 将状态置为运行中
            this.serviceState = ServiceState.RUNNING;
            break;
        case RUNNING:
        case START_FAILED:
        case SHUTDOWN_ALREADY:
            throw new MQClientException("The PushConsumer service state not OK, maybe started once, "
                + this.serviceState
                + FAQUrl.suggestTodo(FAQUrl.CLIENT_SERVICE_NOT_OK),
                null);
        default:
            break;
    }
    // 更新topic路由信息,主要通过向 NameServer 发送 GET_ROUTEINTO_BY_TOPIC 请求来获取最新的 topic 路由信息,然后更新内部消费者的订阅信息和生产者的发布信息
    this.updateTopicSubscribeInfoWhenSubscriptionChanged();
    // 向 Broker 发送 CHECK_CLIENT_CONFIG 命令检查客户端的配置,主要检查订阅表达式的正确性,Broker 处理对应的命令的处理器为 ClientManageProcessor
    this.mQClientFactory.checkClientInBroker();
    // 向所有 Broker 发送心跳请求
    this.mQClientFactory.sendHeartbeatToAllBrokerWithLock();
    // 启动完成立刻做一次 rebanlance
    this.mQClientFactory.rebalanceImmediately();
}

rebanlance 是消息消费过程中一个重要的流程,我们单独分析。Consumer 启动流程和 Producer 启动流程复用了很多逻辑,需要结合两篇文章一起来看。

 类似资料: