概述
RocketMQ消息发送方式:同步(sync)、异步(async)、单向(oneway)
消息Message简介
org.apache.rocketmq.common.message.Message
public class Message implements Serializable {
private static final long serialVersionUID = 8445773977080406428L;
private String topic;//消息主题
private int flag;//消息flag,RocketMQ不做处理
private Map<String, String> properties;//扩展属性
private byte[] body;//消息体
private String transactionId;//事务消息事务id
其中扩展属性包括以下四个:
- tag:消息tag,用于消息过滤
- keys:Message索引键,多个用空格隔开,RocketMQ根据这些key快速检索消息
- waitStoreMsgOK:消息发送时,是否等待消息存储完成后再返回。
- delayTimeLevel:消息延迟级别,用于延迟消息或消息重试
生产者启动流程
org.apache.rocketmq.client.producer.DefaultMQProducer
核心属性如下
属性名 | 含义 |
---|---|
producerGroup | 生产组 |
createTopicKey | 默认topic |
defaultTopicQueueNums | 默认主题在每一个broker队列的数量 |
sendMsgTimeout | 消息发送超时时间 3秒 |
compressMsgBodyOverHowmuch | 消息体超过该值则压缩 |
retryTimesWhenSendFailed | 同步消息重试次数,2次。包含发送一次,一个消息最终为三次 |
retryTimesWhenSendAsyncFailed | 异步发送消息重试次数,默认2次 |
retryAnotherBrokerWhenNotStoreOK | 消息重试选择另一个broker时,是否不等待存储结果就返回,默认为false |
maxMessageSize | 4M |
消息生产者启动流程
org.apache.rocketmq.client.producer.DefaultMQProducer#start
启动流程如下图:
消息发送流程
核心流程我们可以分为以下步骤查看:
DefaultMQProducerImpl#sendDefaultImpl
这个方法作为消息发送的核心方法,主要处理以下:
- tryToFindTopicPublishInfo 寻找消息的路由信息
- selectOneMessageQueue 选择消息队列需要发送的队列
- sendKernelImpl 发送消息
- updateFaultItem 更新发送失败的broker信息
- 发送消息出现异常时,处理各个异常信息
- 返回最终的结果
this.tryToFindTopicPublishInfo(msg.getTopic())
消息发送的核心方法,方法查找对应的消息路由信息,为消息发送做准备,该方法返回TopicPublishInfo。
TopicPublishInfo 属性如下:
属性 | |
---|---|
private boolean orderTopic = false; | 是否为顺序消息 |
private List<MessageQueue> messageQueueList | 主题队列的消息队列 |
private volatile ThreadLocalIndex sendWhichQueue | 没选择一次消息队列,该值会增加1 |
private TopicRouteData topicRouteData | topicRouteData |
TopicRouteData 属性如下
属性 | |
---|---|
private String orderTopicConf | 顺序消息配置 |
private List<QueueData> queueDatas | topic队列元数据,包含brokerName,readQueueNums,writeQueueNums,perm,topicSynFlag |
List<BrokerData> brokerDatas | topic分布的broker元数据,包含 cluster,brokerName,brokerAddrs |
HashMap<String/* brokerAddr /, List<String>/ Filter Server */> filterServerTable | broker上的过滤服务器地址列表 |
DefaultMQProducerImpl#tryToFindTopicPublishInfo
private TopicPublishInfo tryToFindTopicPublishInfo(final String topic) {
//本地缓存获取 TopicPublishInfo
TopicPublishInfo topicPublishInfo = this.topicPublishInfoTable.get(topic);
//如果没有缓存,或者缓存失效则从NameServer获取
if (null == topicPublishInfo || !topicPublishInfo.ok()) {
this.topicPublishInfoTable.putIfAbsent(topic, new TopicPublishInfo());
this.mQClientFactory.updateTopicRouteInfoFromNameServer(topic);
topicPublishInfo = this.topicPublishInfoTable.get(topic);
}
if (topicPublishInfo.isHaveTopicRouterInfo() || topicPublishInfo.ok()) {
return topicPublishInfo;
} else {
this.mQClientFactory.updateTopicRouteInfoFromNameServer(topic, true, this.defaultMQProducer);
topicPublishInfo = this.topicPublishInfoTable.get(topic);
return topicPublishInfo;
}
}
最终调用 MQClientInstance#updateTopicRouteInfoFromNameServer
- 从NameServer获取TopicRouteData 数据
简化后代码
TopicRouteData topicRouteData = this.mQClientAPIImpl.getDefaultTopicRouteInfoFromNameServer(defaultMQProducer.getCreateTopicKey(),
1000 * 3);
- 判断TopicRouteData是否改变过,改变过则更新
- 需要更新则更新对应的brokerAddrTable、topicRouteTable
MessageQueue mqSelected = this.selectOneMessageQueue(topicPublishInfo, lastBrokerName);
获取对应要发送的消息队列。一个MessageQueue 包含topic、brokerName、queueId。
- 默认sendLatencyFaultEnable 为false,则直接调用tpInfo.selectOneMessageQueue(lastBrokerName)
public MessageQueue selectOneMessageQueue(final String lastBrokerName) {
if (lastBrokerName == null) {
return selectOneMessageQueue();
} else {
int index = this.sendWhichQueue.getAndIncrement();
for (int i = 0; i < this.messageQueueList.size(); i++) {
int pos = Math.abs(index++) % this.messageQueueList.size();
if (pos < 0)
pos = 0;
MessageQueue mq = this.messageQueueList.get(pos);
if (!mq.getBrokerName().equals(lastBrokerName)) {
return mq;
}
}
return selectOneMessageQueue();
}
}
public MessageQueue selectOneMessageQueue() {
int index = this.sendWhichQueue.getAndIncrement();
int pos = Math.abs(index) % this.messageQueueList.size();
if (pos < 0)
pos = 0;
return this.messageQueueList.get(pos);
}
获取增量index,取余 然后返回对应的MessageQueue。
如果上次已经发送消息,存在lastBrokerName,则需要获取非lastBrokerName的broker。
- 如果故障延迟机制启用,即sendLatencyFaultEnable 为true。
-1. 如果启用故障延迟,则通过latencyFaultTolerance.isAvailable判断对应的broker是否可用
-2. 如果可用则会维护latencyFaultTolerance。
DefaultMQProducerImpl#sendKernelImpl
/**
*
* @param msg 待发送消息
* @param mq 消息将发送到该队列
* @param communicationMode 消息发送模式 sync/async/oneway
* @param sendCallback 消息回调函数
* @param topicPublishInfo 主题路由信息
* @param timeout 消息超时时间
*/
private SendResult sendKernelImpl(final Message msg,
final MessageQueue mq,
final CommunicationMode communicationMode,
final SendCallback sendCallback,
final TopicPublishInfo topicPublishInfo,
final long timeout)
- 获取broker地址
- 消息设置全局id,消息体超过4k,则压缩并设置sysFlag 为MessageSysFlag.COMPRESSED_FLAG。事务消息则设置sysFlag为MessageSysFlag.TRANSACTION_PREPARED_TYPE。
- 注册消息hook函数
- 构建消息SendMessageRequestHeader
- MQClientAPIImpl#sendMessage
- NettyRemotingClient#invokeSync