2.4 RoundRobinLoadBalance

本节,我们来看一下 Dubbo 中加权轮询负载均衡的实现 RoundRobinLoadBalance。在详细分析源码前,我们先来了解一下什么是加权轮询。这里从最简单的轮询开始讲起,所谓轮询是指将请求轮流分配给每台服务器。举个例子,我们有三台服务器 A、B、C。我们将第一个请求分配给服务器 A,第二个请求分配给服务器 B,第三个请求分配给服务器 C,第四个请求再次分配给服务器 A。这个过程就叫做轮询。轮询是一种无状态负载均衡算法,实现简单,适用于每台服务器性能相近的场景下。但现实情况下,我们并不能保证每台服务器性能均相近。如果我们将等量的请求分配给性能较差的服务器,这显然是不合理的。因此,这个时候我们需要对轮询过程进行加权,以调控每台服务器的负载。经过加权后,每台服务器能够得到的请求数比例,接近或等于他们的权重比。比如服务器 A、B、C 权重比为 5:2:1。那么在8次请求中,服务器 A 将收到其中的5次请求,服务器 B 会收到其中的2次请求,服务器 C 则收到其中的1次请求。

以上就是加权轮询的算法思想,搞懂了这个思想,接下来我们就可以分析源码了。我们先来看一下 2.6.4 版本的 RoundRobinLoadBalance。

  1. public class RoundRobinLoadBalance extends AbstractLoadBalance {
  2. public static final String NAME = "roundrobin";
  3. private final ConcurrentMap<String, AtomicPositiveInteger> sequences =
  4. new ConcurrentHashMap<String, AtomicPositiveInteger>();
  5. @Override
  6. protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
  7. // key = 全限定类名 + "." + 方法名,比如 com.xxx.DemoService.sayHello
  8. String key = invokers.get(0).getUrl().getServiceKey() + "." + invocation.getMethodName();
  9. int length = invokers.size();
  10. // 最大权重
  11. int maxWeight = 0;
  12. // 最小权重
  13. int minWeight = Integer.MAX_VALUE;
  14. final LinkedHashMap<Invoker<T>, IntegerWrapper> invokerToWeightMap = new LinkedHashMap<Invoker<T>, IntegerWrapper>();
  15. // 权重总和
  16. int weightSum = 0;
  17. // 下面这个循环主要用于查找最大和最小权重,计算权重总和等
  18. for (int i = 0; i < length; i++) {
  19. int weight = getWeight(invokers.get(i), invocation);
  20. // 获取最大和最小权重
  21. maxWeight = Math.max(maxWeight, weight);
  22. minWeight = Math.min(minWeight, weight);
  23. if (weight > 0) {
  24. // 将 weight 封装到 IntegerWrapper 中
  25. invokerToWeightMap.put(invokers.get(i), new IntegerWrapper(weight));
  26. // 累加权重
  27. weightSum += weight;
  28. }
  29. }
  30. // 查找 key 对应的对应 AtomicPositiveInteger 实例,为空则创建。
  31. // 这里可以把 AtomicPositiveInteger 看成一个黑盒,大家只要知道
  32. // AtomicPositiveInteger 用于记录服务的调用编号即可。至于细节,
  33. // 大家如果感兴趣,可以自行分析
  34. AtomicPositiveInteger sequence = sequences.get(key);
  35. if (sequence == null) {
  36. sequences.putIfAbsent(key, new AtomicPositiveInteger());
  37. sequence = sequences.get(key);
  38. }
  39. // 获取当前的调用编号
  40. int currentSequence = sequence.getAndIncrement();
  41. // 如果最小权重小于最大权重,表明服务提供者之间的权重是不相等的
  42. if (maxWeight > 0 && minWeight < maxWeight) {
  43. // 使用调用编号对权重总和进行取余操作
  44. int mod = currentSequence % weightSum;
  45. // 进行 maxWeight 次遍历
  46. for (int i = 0; i < maxWeight; i++) {
  47. // 遍历 invokerToWeightMap
  48. for (Map.Entry<Invoker<T>, IntegerWrapper> each : invokerToWeightMap.entrySet()) {
  49. // 获取 Invoker
  50. final Invoker<T> k = each.getKey();
  51. // 获取权重包装类 IntegerWrapper
  52. final IntegerWrapper v = each.getValue();
  53. // 如果 mod = 0,且权重大于0,此时返回相应的 Invoker
  54. if (mod == 0 && v.getValue() > 0) {
  55. return k;
  56. }
  57. // mod != 0,且权重大于0,此时对权重和 mod 分别进行自减操作
  58. if (v.getValue() > 0) {
  59. v.decrement();
  60. mod--;
  61. }
  62. }
  63. }
  64. }
  65. // 服务提供者之间的权重相等,此时通过轮询选择 Invoker
  66. return invokers.get(currentSequence % length);
  67. }
  68. // IntegerWrapper 是一个 int 包装类,主要包含了一个自减方法。
  69. private static final class IntegerWrapper {
  70. private int value;
  71. public void decrement() {
  72. this.value--;
  73. }
  74. // 省略部分代码
  75. }
  76. }

如上,RoundRobinLoadBalance 的每行代码都不是很难理解,但是将它们组合在一起之后,就不是很好理解了。所以下面我们举例进行说明,假设我们有三台服务器 servers = [A, B, C],对应的权重为 weights = [2, 5, 1]。接下来对上面的逻辑进行简单的模拟。

mod = 0:满足条件,此时直接返回服务器 A

mod = 1:需要进行一次递减操作才能满足条件,此时返回服务器 B

mod = 2:需要进行两次递减操作才能满足条件,此时返回服务器 C

mod = 3:需要进行三次递减操作才能满足条件,经过递减后,服务器权重为 [1, 4, 0],此时返回服务器 A

mod = 4:需要进行四次递减操作才能满足条件,经过递减后,服务器权重为 [0, 4, 0],此时返回服务器 B

mod = 5:需要进行五次递减操作才能满足条件,经过递减后,服务器权重为 [0, 3, 0],此时返回服务器 B

mod = 6:需要进行六次递减操作才能满足条件,经过递减后,服务器权重为 [0, 2, 0],此时返回服务器 B

mod = 7:需要进行七次递减操作才能满足条件,经过递减后,服务器权重为 [0, 1, 0],此时返回服务器 B

经过8次调用后,我们得到的负载均衡结果为 [A, B, C, A, B, B, B, B],次数比 A:B:C = 2:5:1,等于权重比。当 sequence = 8 时,mod = 0,此时重头再来。从上面的模拟过程可以看出,当 mod >= 3 后,服务器 C 就不会被选中了,因为它的权重被减为0了。当 mod >= 4 后,服务器 A 的权重被减为0,此后 A 就不会再被选中。

以上是 2.6.4 版本的 RoundRobinLoadBalance 分析过程,2.6.4 版本的 RoundRobinLoadBalance 在某些情况下存在着比较严重的性能问题,该问题最初是在 issue #2578 中被反馈出来。问题出在了 Invoker 的返回时机上,RoundRobinLoadBalance 需要在mod == 0 && v.getValue() > 0 条件成立的情况下才会被返回相应的 Invoker。假如 mod 很大,比如 10000,50000,甚至更大时,doSelect 方法需要进行很多次计算才能将 mod 减为0。由此可知,doSelect 的效率与 mod 有关,时间复杂度为 O(mod)。mod 又受最大权重 maxWeight 的影响,因此当某个服务提供者配置了非常大的权重,此时 RoundRobinLoadBalance 会产生比较严重的性能问题。这个问题被反馈后,社区很快做了回应。并对 RoundRobinLoadBalance 的代码进行了重构,将时间复杂度优化至了常量级别。这个优化可以说很好了,下面我们来学习一下优化后的代码。

  1. public class RoundRobinLoadBalance extends AbstractLoadBalance {
  2. public static final String NAME = "roundrobin";
  3. private final ConcurrentMap<String, AtomicPositiveInteger> sequences = new ConcurrentHashMap<String, AtomicPositiveInteger>();
  4. private final ConcurrentMap<String, AtomicPositiveInteger> indexSeqs = new ConcurrentHashMap<String, AtomicPositiveInteger>();
  5. @Override
  6. protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
  7. String key = invokers.get(0).getUrl().getServiceKey() + "." + invocation.getMethodName();
  8. int length = invokers.size();
  9. int maxWeight = 0;
  10. int minWeight = Integer.MAX_VALUE;
  11. final List<Invoker<T>> invokerToWeightList = new ArrayList<>();
  12. // 查找最大和最小权重
  13. for (int i = 0; i < length; i++) {
  14. int weight = getWeight(invokers.get(i), invocation);
  15. maxWeight = Math.max(maxWeight, weight);
  16. minWeight = Math.min(minWeight, weight);
  17. if (weight > 0) {
  18. invokerToWeightList.add(invokers.get(i));
  19. }
  20. }
  21. // 获取当前服务对应的调用序列对象 AtomicPositiveInteger
  22. AtomicPositiveInteger sequence = sequences.get(key);
  23. if (sequence == null) {
  24. // 创建 AtomicPositiveInteger,默认值为0
  25. sequences.putIfAbsent(key, new AtomicPositiveInteger());
  26. sequence = sequences.get(key);
  27. }
  28. // 获取下标序列对象 AtomicPositiveInteger
  29. AtomicPositiveInteger indexSeq = indexSeqs.get(key);
  30. if (indexSeq == null) {
  31. // 创建 AtomicPositiveInteger,默认值为 -1
  32. indexSeqs.putIfAbsent(key, new AtomicPositiveInteger(-1));
  33. indexSeq = indexSeqs.get(key);
  34. }
  35. if (maxWeight > 0 && minWeight < maxWeight) {
  36. length = invokerToWeightList.size();
  37. while (true) {
  38. int index = indexSeq.incrementAndGet() % length;
  39. int currentWeight = sequence.get() % maxWeight;
  40. // 每循环一轮(index = 0),重新计算 currentWeight
  41. if (index == 0) {
  42. currentWeight = sequence.incrementAndGet() % maxWeight;
  43. }
  44. // 检测 Invoker 的权重是否大于 currentWeight,大于则返回
  45. if (getWeight(invokerToWeightList.get(index), invocation) > currentWeight) {
  46. return invokerToWeightList.get(index);
  47. }
  48. }
  49. }
  50. // 所有 Invoker 权重相等,此时进行普通的轮询即可
  51. return invokers.get(sequence.incrementAndGet() % length);
  52. }
  53. }

上面代码的逻辑是这样的,每进行一轮循环,重新计算 currentWeight。如果当前 Invoker 权重大于 currentWeight,则返回该 Invoker。下面举例说明,假设服务器 [A, B, C] 对应权重 [5, 2, 1]。

第一轮循环,currentWeight = 1,可返回 A 和 B

第二轮循环,currentWeight = 2,返回 A

第三轮循环,currentWeight = 3,返回 A

第四轮循环,currentWeight = 4,返回 A

第五轮循环,currentWeight = 0,返回 A, B, C

如上,这里的一轮循环是指 index 再次变为0所经历过的循环,这里可以把 index = 0 看做是一轮循环的开始。每一轮循环的次数与 Invoker 的数量有关,Invoker 数量通常不会太多,所以我们可以认为上面代码的时间复杂度为常数级。

重构后的 RoundRobinLoadBalance 看起来已经很不错了,但是在代码更新不久后,很快又被重构了。这次重构原因是新的 RoundRobinLoadBalance 在某些情况下选出的服务器序列不够均匀。比如,服务器 [A, B, C] 对应权重 [5, 1, 1]。进行7次负载均衡后,选择出来的序列为 [A, A, A, A, A, B, C]。前5个请求全部都落在了服务器 A上,这将会使服务器 A 短时间内接收大量的请求,压力陡增。而 B 和 C 此时无请求,处于空闲状态。而我们期望的结果是这样的 [A, A, B, A, C, A, A],不同服务器可以穿插获取请求。为了增加负载均衡结果的平滑性,社区再次对 RoundRobinLoadBalance 的实现进行了重构,这次重构参考自 Nginx 的平滑加权轮询负载均衡。每个服务器对应两个权重,分别为 weight 和 currentWeight。其中 weight 是固定的,currentWeight 会动态调整,初始值为0。当有新的请求进来时,遍历服务器列表,让它的 currentWeight 加上自身权重。遍历完成后,找到最大的 currentWeight,并将其减去权重总和,然后返回相应的服务器即可。

上面描述不是很好理解,下面还是举例进行说明。这里仍然使用服务器 [A, B, C] 对应权重 [5, 1, 1] 的例子说明,现在有7个请求依次进入负载均衡逻辑,选择过程如下:

请求编号currentWeight 数组选择结果减去权重总和后的 currentWeight 数组
1[5, 1, 1]A[-2, 1, 1]
2[3, 2, 2]A[-4, 2, 2]
3[1, 3, 3]B[1, -4, 3]
4[6, -3, 4]A[-1, -3, 4]
5[4, -2, 5]C[4, -2, -2]
6[9, -1, -1]A[2, -1, -1]
7[7, 0, 0]A[0, 0, 0]

如上,经过平滑性处理后,得到的服务器序列为 [A, A, B, A, C, A, A],相比之前的序列 [A, A, A, A, A, B, C],分布性要好一些。初始情况下 currentWeight = [0, 0, 0],第7个请求处理完后,currentWeight 再次变为 [0, 0, 0]。

以上就是平滑加权轮询的计算过程,接下来,我们来看看 Dubbo-2.6.5 是如何实现上面的计算过程的。

  1. public class RoundRobinLoadBalance extends AbstractLoadBalance {
  2. public static final String NAME = "roundrobin";
  3. private static int RECYCLE_PERIOD = 60000;
  4. protected static class WeightedRoundRobin {
  5. // 服务提供者权重
  6. private int weight;
  7. // 当前权重
  8. private AtomicLong current = new AtomicLong(0);
  9. // 最后一次更新时间
  10. private long lastUpdate;
  11. public void setWeight(int weight) {
  12. this.weight = weight;
  13. // 初始情况下,current = 0
  14. current.set(0);
  15. }
  16. public long increaseCurrent() {
  17. // current = current + weight;
  18. return current.addAndGet(weight);
  19. }
  20. public void sel(int total) {
  21. // current = current - total;
  22. current.addAndGet(-1 * total);
  23. }
  24. }
  25. // 嵌套 Map 结构,存储的数据结构示例如下:
  26. // {
  27. // "UserService.query": {
  28. // "url1": WeightedRoundRobin@123,
  29. // "url2": WeightedRoundRobin@456,
  30. // },
  31. // "UserService.update": {
  32. // "url1": WeightedRoundRobin@123,
  33. // "url2": WeightedRoundRobin@456,
  34. // }
  35. // }
  36. // 最外层为服务类名 + 方法名,第二层为 url 到 WeightedRoundRobin 的映射关系。
  37. // 这里我们可以将 url 看成是服务提供者的 id
  38. private ConcurrentMap<String, ConcurrentMap<String, WeightedRoundRobin>> methodWeightMap = new ConcurrentHashMap<String, ConcurrentMap<String, WeightedRoundRobin>>();
  39. // 原子更新锁
  40. private AtomicBoolean updateLock = new AtomicBoolean();
  41. @Override
  42. protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
  43. String key = invokers.get(0).getUrl().getServiceKey() + "." + invocation.getMethodName();
  44. // 获取 url 到 WeightedRoundRobin 映射表,如果为空,则创建一个新的
  45. ConcurrentMap<String, WeightedRoundRobin> map = methodWeightMap.get(key);
  46. if (map == null) {
  47. methodWeightMap.putIfAbsent(key, new ConcurrentHashMap<String, WeightedRoundRobin>());
  48. map = methodWeightMap.get(key);
  49. }
  50. int totalWeight = 0;
  51. long maxCurrent = Long.MIN_VALUE;
  52. // 获取当前时间
  53. long now = System.currentTimeMillis();
  54. Invoker<T> selectedInvoker = null;
  55. WeightedRoundRobin selectedWRR = null;
  56. // 下面这个循环主要做了这样几件事情:
  57. // 1. 遍历 Invoker 列表,检测当前 Invoker 是否有
  58. // 相应的 WeightedRoundRobin,没有则创建
  59. // 2. 检测 Invoker 权重是否发生了变化,若变化了,
  60. // 则更新 WeightedRoundRobin 的 weight 字段
  61. // 3. 让 current 字段加上自身权重,等价于 current += weight
  62. // 4. 设置 lastUpdate 字段,即 lastUpdate = now
  63. // 5. 寻找具有最大 current 的 Invoker,以及 Invoker 对应的 WeightedRoundRobin,
  64. // 暂存起来,留作后用
  65. // 6. 计算权重总和
  66. for (Invoker<T> invoker : invokers) {
  67. String identifyString = invoker.getUrl().toIdentityString();
  68. WeightedRoundRobin weightedRoundRobin = map.get(identifyString);
  69. int weight = getWeight(invoker, invocation);
  70. if (weight < 0) {
  71. weight = 0;
  72. }
  73. // 检测当前 Invoker 是否有对应的 WeightedRoundRobin,没有则创建
  74. if (weightedRoundRobin == null) {
  75. weightedRoundRobin = new WeightedRoundRobin();
  76. // 设置 Invoker 权重
  77. weightedRoundRobin.setWeight(weight);
  78. // 存储 url 唯一标识 identifyString 到 weightedRoundRobin 的映射关系
  79. map.putIfAbsent(identifyString, weightedRoundRobin);
  80. weightedRoundRobin = map.get(identifyString);
  81. }
  82. // Invoker 权重不等于 WeightedRoundRobin 中保存的权重,说明权重变化了,此时进行更新
  83. if (weight != weightedRoundRobin.getWeight()) {
  84. weightedRoundRobin.setWeight(weight);
  85. }
  86. // 让 current 加上自身权重,等价于 current += weight
  87. long cur = weightedRoundRobin.increaseCurrent();
  88. // 设置 lastUpdate,表示近期更新过
  89. weightedRoundRobin.setLastUpdate(now);
  90. // 找出最大的 current
  91. if (cur > maxCurrent) {
  92. maxCurrent = cur;
  93. // 将具有最大 current 权重的 Invoker 赋值给 selectedInvoker
  94. selectedInvoker = invoker;
  95. // 将 Invoker 对应的 weightedRoundRobin 赋值给 selectedWRR,留作后用
  96. selectedWRR = weightedRoundRobin;
  97. }
  98. // 计算权重总和
  99. totalWeight += weight;
  100. }
  101. // 对 <identifyString, WeightedRoundRobin> 进行检查,过滤掉长时间未被更新的节点。
  102. // 该节点可能挂了,invokers 中不包含该节点,所以该节点的 lastUpdate 长时间无法被更新。
  103. // 若未更新时长超过阈值后,就会被移除掉,默认阈值为60秒。
  104. if (!updateLock.get() && invokers.size() != map.size()) {
  105. if (updateLock.compareAndSet(false, true)) {
  106. try {
  107. ConcurrentMap<String, WeightedRoundRobin> newMap = new ConcurrentHashMap<String, WeightedRoundRobin>();
  108. // 拷贝
  109. newMap.putAll(map);
  110. // 遍历修改,即移除过期记录
  111. Iterator<Entry<String, WeightedRoundRobin>> it = newMap.entrySet().iterator();
  112. while (it.hasNext()) {
  113. Entry<String, WeightedRoundRobin> item = it.next();
  114. if (now - item.getValue().getLastUpdate() > RECYCLE_PERIOD) {
  115. it.remove();
  116. }
  117. }
  118. // 更新引用
  119. methodWeightMap.put(key, newMap);
  120. } finally {
  121. updateLock.set(false);
  122. }
  123. }
  124. }
  125. if (selectedInvoker != null) {
  126. // 让 current 减去权重总和,等价于 current -= totalWeight
  127. selectedWRR.sel(totalWeight);
  128. // 返回具有最大 current 的 Invoker
  129. return selectedInvoker;
  130. }
  131. // should not happen here
  132. return invokers.get(0);
  133. }
  134. }

以上就是 Dubbo-2.6.5 版本的 RoundRobinLoadBalance,大家如果能够理解平滑加权轮询算法的计算过程,再配合代码中注释,理解上面的代码应该不难。