RocketMQ分析1之Producer

原文链接: https://my.oschina.net/u/2358147/blog/689935
import java.util.concurrent.TimeUnit;

import com.alibaba.rocketmq.client.exception.MQClientException;
import com.alibaba.rocketmq.client.producer.DefaultMQProducer;
import com.alibaba.rocketmq.client.producer.SendResult;
import com.alibaba.rocketmq.common.message.Message;

public class Producer {
    public static void main(String[] args) throws MQClientException, InterruptedException {
        /**
         * 一个应用创建一个Producer,由应用来维护此对象,可以设置为全局对象或者单例
         * 注意:ProducerGroupName需要由应用来保证唯一
         * ProducerGroup这个概念发送普通的消息时,作用不大,但是发送分布式事务消息时,比较关键,          * 因为服务器会回查这个Group下的任意一个Producer          */         final DefaultMQProducer producer = new DefaultMQProducer("ProducerGroupName");         producer.setNamesrvAddr("172.30.2.27:9886");         producer.setInstanceName("Producer");         /**          * Producer对象在使用之前必须要调用start初始化,初始化一次即可
         * 注意:切记不可以在每次发送消息时,都调用start方法          */         producer.start();         /**          * 下面这段代码表明一个Producer对象可以发送多个topic,多个tag的消息。          * 注意:send方法是同步调用,只要不抛异常就标识成功。但是发送成功也可会有多种状态,
         * 例如消息写入Master成功,但是Slave不成功,这种情况消息属于成功,但是对于个别应用如果对消息可靠性要求极高,
         * 需要对这种情况做处理。另外,消息可能会存在发送失败的情况,失败重试由应用来处理。          */         for (int i = 0; i < 10; i++) {             try {                 {                     Message msg = new Message("TopicTest1", // topic                             "TagA", // tag ,                               "OrderID001", // key , 最好用唯一的编号,比如订单号码?交易流水号?                             ("Hello MetaQA").getBytes());// body , 实际应用场景中可以使用Json数据字符串,传递相应的内容                     SendResult sendResult = producer.send(msg);                     System.out.println(sendResult);                 }                 {                     Message msg = new Message("TopicTest2", // topic                             "TagB", // tag                             "OrderID0034", // key                             ("Hello MetaQB").getBytes());// body                     SendResult sendResult = producer.send(msg);                     System.out.println(sendResult);                 }                 {                     Message msg = new Message("TopicTest3", // topic                             "TagC", // tag                             "OrderID061", // key                             ("Hello MetaQC").getBytes());// body                     SendResult sendResult = producer.send(msg);                     System.out.println(sendResult);                 }             } catch (Exception e) {                 e.printStackTrace();             }             TimeUnit.MILLISECONDS.sleep(1000);         }         /**          * 应用退出时,要调用shutdown来清理资源,关闭网络连接,从MetaQ服务器上注销自己          * 注意:我们建议应用在JBOSS、Tomcat等容器的退出钩子里调用shutdown方法          */         // producer.shutdown();         Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {             public void run() {                 producer.shutdown();             }         }));         System.exit(0);     } }

 

调用原理图:

RocketMQ分析1之Producer_第1张图片

分析源码:

producer.send(msg);这段代码底层调用一下方法(发送消息超时时间默认sendMsgTimeout = 3000):

 public SendResult send(Message msg, long timeout) throws MQClientException, RemotingException,
            MQBrokerException, InterruptedException {
        return this.sendDefaultImpl(msg, CommunicationMode.SYNC, null, timeout);
    }

具体实现:

private SendResult sendDefaultImpl(//
            Message msg,//
            final CommunicationMode communicationMode,//
            final SendCallback sendCallback, final long timeout//
    ) throws MQClientException, RemotingException, MQBrokerException, InterruptedException {
        this.makeSureStateOK();
        Validators.checkMessage(msg, this.defaultMQProducer);

        final long maxTimeout = this.defaultMQProducer.getSendMsgTimeout() + 1000;
        final long beginTimestamp = System.currentTimeMillis();
        long endTimestamp = beginTimestamp;
        TopicPublishInfo topicPublishInfo = this.tryToFindTopicPublishInfo(msg.getTopic());
        if (topicPublishInfo != null && topicPublishInfo.ok()) {
            MessageQueue mq = null;
            Exception exception = null;
            SendResult sendResult = null;
            int timesTotal = 1 + this.defaultMQProducer.getRetryTimesWhenSendFailed();
            int times = 0;
            String[] brokersSent = new String[timesTotal];
            for (; times < timesTotal && (endTimestamp - beginTimestamp) < maxTimeout; times++) {
                String lastBrokerName = null == mq ? null : mq.getBrokerName();
                MessageQueue tmpmq = topicPublishInfo.selectOneMessageQueue(lastBrokerName);
                if (tmpmq != null) {
                    mq = tmpmq;
                    brokersSent[times] = mq.getBrokerName();
                    try {
                        sendResult = this.sendKernelImpl(msg, mq, communicationMode, sendCallback, timeout);
                        endTimestamp = System.currentTimeMillis();
                        switch (communicationMode) {
                        case ASYNC:
                            return null;
                        case ONEWAY:
                            return null;
                        case SYNC:
                            if (sendResult.getSendStatus() != SendStatus.SEND_OK) {
                                if (this.defaultMQProducer.isRetryAnotherBrokerWhenNotStoreOK()) {
                                    continue;
                                }
                            }

                            return sendResult;
                        default:
                            break;
                        }
                    }
                    catch (RemotingException e) {
                        log.warn("sendKernelImpl exception", e);
                        log.warn(msg.toString());
                        exception = e;
                        endTimestamp = System.currentTimeMillis();
                        continue;
                    }
                    catch (MQClientException e) {
                        log.warn("sendKernelImpl exception", e);
                        log.warn(msg.toString());
                        exception = e;
                        endTimestamp = System.currentTimeMillis();
                        continue;
                    }
                    catch (MQBrokerException e) {
                        log.warn("sendKernelImpl exception", e);
                        log.warn(msg.toString());
                        exception = e;
                        endTimestamp = System.currentTimeMillis();
                        switch (e.getResponseCode()) {
                        case ResponseCode.TOPIC_NOT_EXIST:
                        case ResponseCode.SERVICE_NOT_AVAILABLE:
                        case ResponseCode.SYSTEM_ERROR:
                        case ResponseCode.NO_PERMISSION:
                        case ResponseCode.NO_BUYER_ID:
                        case ResponseCode.NOT_IN_CURRENT_UNIT:
                            continue;
                        default:
                            if (sendResult != null) {
                                return sendResult;
                            }

                            throw e;
                        }
                    }
                    catch (InterruptedException e) {
                        log.warn("sendKernelImpl exception", e);
                        log.warn(msg.toString());
                        throw e;
                    }
                }
                else {
                    break;
                }
            } // end of for

            if (sendResult != null) {
                return sendResult;
            }

            String info =
                    String.format("Send [%d] times, still failed, cost [%d]ms, Topic: %s, BrokersSent: %s", //
                        times, //
                        (System.currentTimeMillis() - beginTimestamp), //
                        msg.getTopic(),//
                        Arrays.toString(brokersSent));

            info += FAQUrl.suggestTodo(FAQUrl.SEND_MSG_FAILED);

            throw new MQClientException(info, exception);
        }

        List nsList = this.getmQClientFactory().getMQClientAPIImpl().getNameServerAddressList();
        if (null == nsList || nsList.isEmpty()) {
            throw new MQClientException("No name server address, please set it."
                    + FAQUrl.suggestTodo(FAQUrl.NAME_SERVER_ADDR_NOT_EXIST_URL), null);
        }

        throw new MQClientException("No route info of this topic, " + msg.getTopic()
                + FAQUrl.suggestTodo(FAQUrl.NO_TOPIC_ROUTE_INFO), null);
    }

 

转载于:https://my.oschina.net/u/2358147/blog/689935

你可能感兴趣的:(RocketMQ分析1之Producer)