Rocketmq源码分析DefaultMQProducer

1.简述
该篇主要简单介绍下RocketMq默认的发送消息实现DefaultMQProducerImpl

2.源码分析
以sendDefaultImpl函数为切入点进行讲解.
2.1sendDefaultImpl入参

private SendResult sendDefaultImpl(//
            Message msg,//消息内容
            final CommunicationMode communicationMode,// 消息发送模式 默认 异步
            final SendCallback sendCallback,//回调结果
             final long timeout//超时时间默认3000秒
    )    

2.2makeSureStateOK()确认服务状态为Running

  private void makeSureStateOK() throws MQClientException {
        if (this.serviceState != ServiceState.RUNNING) {
            throw new MQClientException("The producer service state not OK, "//
                    + this.serviceState//
                    + FAQUrl.suggestTodo(FAQUrl.CLIENT_SERVICE_NOT_OK), null);
        }
    }

2.3 checkMessage 消息内容校验

public static void checkMessage(Message msg, DefaultMQProducer defaultMQProducer)
            throws MQClientException {
        //消息是否为空
        if (null == msg) {
            throw new MQClientException(ResponseCode.MESSAGE_ILLEGAL, "the message is null");
        }
        // topic
        Validators.checkTopic(msg.getTopic());
        // body
        if (null == msg.getBody()) {
            throw new MQClientException(ResponseCode.MESSAGE_ILLEGAL, "the message body is null");
        }
		//body不能空
        if (0 == msg.getBody().length) {
            throw new MQClientException(ResponseCode.MESSAGE_ILLEGAL, "the message body length is zero");
        }
		//消息体 不能超过 1024 * 128
        if (msg.getBody().length > defaultMQProducer.getMaxMessageSize()) {
            throw new MQClientException(ResponseCode.MESSAGE_ILLEGAL,
                    "the message body size over max value, MAX: " + defaultMQProducer.getMaxMessageSize());
        }
    }

2.4 tryToFindTopicPublishInfo 获取 消息推送信息

private TopicPublishInfo tryToFindTopicPublishInfo(final String topic) {
        TopicPublishInfo topicPublishInfo = this.topicPublishInfoTable.get(topic);
        //如果为找到topic数据 或者 消息队列为空 新建
        if (null == topicPublishInfo || !topicPublishInfo.ok()) {
            this.topicPublishInfoTable.putIfAbsent(topic, new TopicPublishInfo());
            this.mQClientFactory.updateTopicRouteInfoFromNameServer(topic);
            topicPublishInfo = this.topicPublishInfoTable.get(topic);
        }
		//若果找到 且 信息存在
        if (topicPublishInfo.isHaveTopicRouterInfo() || (topicPublishInfo != null && topicPublishInfo.ok())) {
            return topicPublishInfo;
        }
        else {
            this.mQClientFactory.updateTopicRouteInfoFromNameServer(topic, true, this.defaultMQProducer);
            topicPublishInfo = this.topicPublishInfoTable.get(topic);
            return topicPublishInfo;
        }
    }

你可能感兴趣的:(消息队列)