1.启用broker故障延迟源码:
public MessageQueue selectOneMessageQueue(final TopicPublishInfo tpInfo, final String lastBrokerName) {
// 默认为false,代表不启用broker故障延迟
if (this.sendLatencyFaultEnable) {
try {
// 随机数且+1
int index = tpInfo.getSendWhichQueue().getAndIncrement();
// 遍历 次数:queue的数量
for (int i = 0; i < tpInfo.getMessageQueueList().size(); i++) {
int pos = Math.abs(index++) % tpInfo.getMessageQueueList().size();
if (pos < 0)
pos = 0;
MessageQueue mq = tpInfo.getMessageQueueList().get(pos);
// 查看找到的queue的broker是否可用
if (latencyFaultTolerance.isAvailable(mq.getBrokerName())) {
// 判断这次选择的broker和上次重试的broker是否一样
if (null == lastBrokerName || mq.getBrokerName().equals(lastBrokerName))
return mq;
}
}
// 如果所有队列都不可用,默认上次发消息失败的broker已经不可用,那么选择一个相对好的broker,不考虑可用性的消息队列
final String notBestBroker = latencyFaultTolerance.pickOneAtLeast();
// 获取该broker的写队列数
// 发消息获取的写队列数, 消费消息获取的是读队列数, 为什么要设置读队列数和写队列数?
int writeQueueNums = tpInfo.getQueueIdByBroker(notBestBroker);
if (writeQueueNums > 0) {
// 其实就是选择新的broker和queue
final MessageQueue mq = tpInfo.selectOneMessageQueue();
if (notBestBroker != null) {
mq.setBrokerName(notBestBroker);
mq.setQueueId(tpInfo.getSendWhichQueue().getAndIncrement() % writeQueueNums);
}
return mq;
} else {
latencyFaultTolerance.remove(notBestBroker);
}
} catch (Exception e) {
log.error("Error occurred when selecting message queue", e);
}
return tpInfo.selectOneMessageQueue();
}
return tpInfo.selectOneMessageQueue(lastBrokerName);
}
2.没有启用broker故障延迟
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();
}
}