RocketMQ中MessageQueue的选择原理

有两种情况,一种是正常发送,一种是发送失败后的重试发送

第一种:正常发送消息

这是正常发送消息的内部逻辑,

1. 通过调用 sendWhichQueue.incrementAndGet() 方法获得一个 index 值

2. 将 index 与队列数取余   得到处理后的 pos 下标值

3. 根据 pos 下标取得应该发送的队列

public MessageQueue selectOneMessageQueue() {
  // 拿到 sendWhichQueue
  int index = this.sendWhichQueue.incrementAndGet();
  // 对 messageQueue 列表长度取余
  int pos = Math.abs(index) % this.messageQueueList.size();
  // 计算出来的 pos 如果小于 0, 就给个兜底 = 0
  if (pos < 0)
    pos = 0;
  return this.messageQueueList.get(pos);
}

这是 sendWhichQueue.incrementAndGet() 方法的逻辑

public int incrementAndGet() {
  Integer index = this.threadLocalIndex.get();
  if (null == index) {
    index = Math.abs(random.nextInt());
    this.threadLocalIndex.set(index);
  }

  this.threadLocalIndex.set(++index);
  return Math.abs(index & POSITIVE_MASK);
}

此方法先判断index是否存在

—— 存在:++index并返回

——不存在:random随机造一个index保存起来

思考:为什么要 ++index 呢?

假设第一次随机到的是 index=11,队列数为5,那么采用取余计算 11%5 为1,所以第一次会选择下标为1的队列,之后每次调用如果让 index 自增,那么就是 12%5=2 ,以此类推最终选择的队列顺序为:

1,2,3,4,0,1,2,3,4,0

没错,实现了线性轮询的负载均衡算法

它可以将流量均匀地分发给不同的 MessageQueue,而 MessageQueue 分布在不同的 Broker 上,这样也达到了对最终 Message 存储的负载均衡,避免造成数据倾斜。

第二种:在发送模式为SYNC时,重试发送消息

目的是为了避开上一次发送失败的Broker,尽量保证发送成功。

lastBrokerName代表上次选择的Broker

1. 首先判断 lastBrokerName 是否为 null , lastBrokerName 只有在重试发送消息时才会有值。所以如果为 null 就代表不是重试发送消息,直接采用第一种方式选择队列。

2. 如果 lastBrokerName 为 null ,代表是重试发送消息,进入重试逻辑

3. 取出 index 并取余计算 pos

4. 遍历所有队列,寻找与上一次选择不一样的队列进行发送消息。

public MessageQueue selectOneMessageQueue(final String lastBrokerName) {
    if (lastBrokerName == null) {
        return selectOneMessageQueue();
    } else {
        for (int i = 0; i < this.messageQueueList.size(); i++) {
            int index = this.sendWhichQueue.incrementAndGet();
            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();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值