负载均衡

在发起RPC远程调用的时候,也就是我们前面经常提的 InvokerInvocationHandler 。在这里面还会进行负载均衡。负载出Invoke节点进行调用。

负载均衡算法

  • Random LoadBalance:随机,按权重设置随机概率。在一个节点上碰撞的概率高,但调用量越大分布越均匀,而且按概率使用权重后也比较均匀,有利于动态调整提供者的权重。
  • RoundRobin LoadBalance: 轮询,按公约后的权重设置轮询比例。存在慢的提供者累积请求的问题, 比如:第二台机器很慢,但没“挂”,当请求调到第二台时就卡在那里久而久之,所有请求都卡在调到第二台上。
  • LeastActive LoadBalance: 最少活跃调用数,如果活跃数相同则随机调用,活跃数指调用前后计数差。使慢的提供者收到更少请求,因为越慢的提供者的调用前后计数差会越大。
  • ConsistentHash LoadBalance:一致性Hash,相同参数的请求总是发到同一提供者。当某一台提供者“挂”时,原本发往该提供者的请求,基于虚拟节点,会平摊到其他提 供者,不会引起剧烈变动。默认只对第一个参数“Hash”,如果要修改, 则配置 o默认使用160份虚拟节点,如果要修改,则配置〈dubbo:parameterkey=”hash.nodes” value=”320” />

14.Dubbo负载均衡源码阅读 - 图1

14.Dubbo负载均衡源码阅读 - 图2

14.Dubbo负载均衡源码阅读 - 图3

  1. protected LoadBalance initLoadBalance(List<Invoker<T>> invokers, Invocation invocation) {
  2. // 这里就是加载 第一张图中的 负载均衡的SPI接口的扩展类
  3. if (CollectionUtils.isNotEmpty(invokers)) {
  4. return ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(invokers.get(0).getUrl()
  5. .getMethodParameter(RpcUtils.getMethodName(invocation), LOADBALANCE_KEY, DEFAULT_LOADBALANCE));
  6. } else {
  7. return ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(DEFAULT_LOADBALANCE);
  8. }
  9. }

14.Dubbo负载均衡源码阅读 - 图4

14.Dubbo负载均衡源码阅读 - 图5

AbstractClusterInvoker.java

  1. /**
  2. * Select a invoker using loadbalance policy.</br>
  3. * a) Firstly, select an invoker using loadbalance. If this invoker is in previously selected list, or,
  4. * if this invoker is unavailable, then continue step b (reselect), otherwise return the first selected invoker</br>
  5. * <p>
  6. * b) Reselection, the validation rule for reselection: selected > available. This rule guarantees that
  7. * the selected invoker has the minimum chance to be one in the previously selected list, and also
  8. * guarantees this invoker is available.
  9. *
  10. * @param loadbalance 负载均衡算法类型
  11. * @param invocation 调用信息封装
  12. * @param invokers 参与负载均衡
  13. * @param selected 排除的,不参与负载均衡
  14. * @return the invoker which will final to do invoke.
  15. * @throws RpcException exception
  16. */
  17. protected Invoker<T> select(LoadBalance loadbalance, Invocation invocation,
  18. List<Invoker<T>> invokers, List<Invoker<T>> selected) throws RpcException {
  19. // 为空直接返回
  20. if (CollectionUtils.isEmpty(invokers)) {
  21. return null;
  22. }
  23. // 从调用信息中拿到调用方法名称
  24. String methodName = invocation == null ? StringUtils.EMPTY : invocation.getMethodName();
  25. // 是否开启粘滞连接
  26. // 这个我们之前在Dubbo高级应用提到过,就是通过 <dubbo:protocol name="dubbo" sticky="true" /> sticky属性配置
  27. // 所谓 sticky连接就是
  28. // 粘滞连接用于有状态服务,尽可能让客户端总是向同一提供者发起调用,除非该提供者“挂了”,再连接另一台。粘滞连接将自动开启延迟连接,以减少长连接数。
  29. boolean sticky = invokers.get(0).getUrl()
  30. .getMethodParameter(methodName, CLUSTER_STICKY_KEY, DEFAULT_CLUSTER_STICKY);
  31. // stickyInvoker缓存了之前使用过的粘滞连接的Invoker
  32. // 如果缓存不是空, 而 该缓存又没包含在最新invokers列表中, 则说明该粘滞连接的Invoker 处理宕机状态
  33. // 则清空缓存
  34. if (stickyInvoker != null && !invokers.contains(stickyInvoker)) {
  35. stickyInvoker = null;
  36. }
  37. // 当前开启了URL粘滞连接 并且 当前已经存在之前调用过的粘滞连接Invoker
  38. // 不参与负载均衡的invoker为空 或者 当前不参与负载均衡的invoker列表中不包含 粘滞连接的缓存
  39. if (sticky && stickyInvoker != null && (selected == null || !selected.contains(stickyInvoker))) {
  40. // 开启了检测是否可以, 那就去检测一下invoker是否可以
  41. // 如果可用,将不再做负载。直接返回粘滞连接的invoke
  42. if (availablecheck && stickyInvoker.isAvailable()) {
  43. return stickyInvoker;
  44. }
  45. }
  46. Invoker<T> invoker = doSelect(loadbalance, invocation, invokers, selected);
  47. // 如果开启了粘滞连接, 则缓存
  48. if (sticky) {
  49. stickyInvoker = invoker;
  50. }
  51. return invoker;
  52. }
  53. private Invoker<T> doSelect(LoadBalance loadbalance, Invocation invocation,
  54. List<Invoker<T>> invokers, List<Invoker<T>> selected) throws RpcException {
  55. // 为空直接返回
  56. if (CollectionUtils.isEmpty(invokers)) {
  57. return null;
  58. }
  59. // 如果只有一个就没有做负载的必要了,直接返回这一个
  60. if (invokers.size() == 1) {
  61. return invokers.get(0);
  62. }
  63. Invoker<T> invoker = loadbalance.select(invokers, getUrl(), invocation);
  64. // 选择出的这个invoker包含在有问题invoker集合selected中,或这个invoker直接是不可用的
  65. if ((selected != null && selected.contains(invoker))
  66. || (!invoker.isAvailable() && getUrl() != null && availablecheck)) {
  67. try {
  68. // 重新负载均衡选择
  69. Invoker<T> rInvoker = reselect(loadbalance, invocation, invokers, selected, availablecheck);
  70. if (rInvoker != null) {
  71. // 选择出了
  72. invoker = rInvoker;
  73. } else {
  74. // 重新选择的结果为null
  75. int index = invokers.indexOf(invoker);
  76. try {
  77. // 拿到第一次负载出invoker的索取, 直接返回
  78. // 事情到了这一步也没办法了, 因为实在选不出invoker了。 管你这个invoker可不可用,直接返回给你就行了
  79. invoker = invokers.get((index + 1) % invokers.size());
  80. } catch (Exception e) {
  81. logger.warn(e.getMessage() + " may because invokers list dynamic change, ignore.", e);
  82. }
  83. }
  84. } catch (Throwable t) {
  85. logger.error("cluster reselect fail reason is :" + t.getMessage() + " if can not solve, you can set cluster.availablecheck=false in url", t);
  86. }
  87. }
  88. return invoker;
  89. }
  90. /**
  91. * 重新选择invoker
  92. * @param loadbalance 负载策略
  93. * @param invocation 包含调用的消息
  94. * @param invokers 对该列表中的invoker负载均衡
  95. * @param selected 被排除的,不参与负载均衡的invoker
  96. * @param availablecheck true:表示检测invoker是否可以 false:不检测
  97. * @return the reselect result to do invoke
  98. * @throws RpcException exception
  99. */
  100. private Invoker<T> reselect(LoadBalance loadbalance, Invocation invocation,
  101. List<Invoker<T>> invokers, List<Invoker<T>> selected, boolean availablecheck) throws RpcException {
  102. // 刚才选择出来的有问题,把数量减掉一个
  103. List<Invoker<T>> reselectInvokers = new ArrayList<>(
  104. invokers.size() > 1 ? (invokers.size() - 1) : invokers.size());
  105. // 循环invoker节点
  106. for (Invoker<T> invoker : invokers) {
  107. // 如果开启节点检测 而 检测的结果是不可用,则进行下一次
  108. if (availablecheck && !invoker.isAvailable()) {
  109. continue;
  110. }
  111. // 代码到这里表示当次循环的invkers可用
  112. // 如果它不是排除的invkers
  113. if (selected == null || !selected.contains(invoker)) {
  114. // 则添加到重新选择出可用invker列表中
  115. reselectInvokers.add(invoker);
  116. }
  117. }
  118. // 重新选择出了可用的, 对这个列表进行负载均衡
  119. if (!reselectInvokers.isEmpty()) {
  120. // 返回负载出的invoker
  121. return loadbalance.select(reselectInvokers, getUrl(), invocation);
  122. }
  123. // 到这里,说明最终从可用的invoker中没有选择出可用的
  124. // 那就试一下从排除的invoker列表中再选一次
  125. // 刚才selected中的invoker不可用, 说不定现在就可用了。 所以这里还是试一试
  126. if (selected != null) {
  127. for (Invoker<T> invoker : selected) {
  128. // 重选出的invoker列表中不包含该invoker。并且 现在这个invoker是可用的
  129. if ((invoker.isAvailable()) && !reselectInvokers.contains(invoker)) {
  130. // 添加到重选的invoker列表
  131. reselectInvokers.add(invoker);
  132. }
  133. }
  134. }
  135. // 如果重选的这个列表有元素, 则进行负载并返回
  136. if (!reselectInvokers.isEmpty()) {
  137. return loadbalance.select(reselectInvokers, getUrl(), invocation);
  138. }
  139. // 最终
  140. // 上面的业务都走过了还是没有选出invoker, 则返回null
  141. return null;
  142. }

AbstractLoadBalance.java

  1. public <T> Invoker<T> select(List<Invoker<T>> invokers, URL url, Invocation invocation) {
  2. if (CollectionUtils.isEmpty(invokers)) {
  3. return null;
  4. }
  5. if (invokers.size() == 1) {
  6. return invokers.get(0);
  7. }
  8. // 真正对invokers进行负载均衡算法
  9. return doSelect(invokers, url, invocation);
  10. }

随机算法

使用方式

  1. <dubbo:reference id="gcService" loadbalance="random" check="false" interface="org.apache.dubbo.gc.GcService"/>

使用场景

  1. 用于服务级别,其适用于,提供者主机性能差别较大的场景。若所有提供者的性能差别不大,则会使该算法变为了纯粹的随机算法。而纯粹的随机算法则可能会出现“负载堆积”问题,即可能存在生成的某些随机数机率较高从而导致某些提供者的负载较大。

RandomLoadBalance.java

  1. /**
  2. * 负载均衡随机算法
  3. */
  4. public class RandomLoadBalance extends AbstractLoadBalance {
  5. public static final String NAME = "random";
  6. @Override
  7. protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
  8. // Number of invokers
  9. int length = invokers.size();
  10. // 用于标识所有invoker的权重是否相同
  11. boolean sameWeight = true;
  12. // 按照invoker的数量生成一个权重的数组
  13. int[] weights = new int[length];
  14. // 先对第一个invoker进行权重, 作为标本
  15. int firstWeight = getWeight(invokers.get(0), invocation);
  16. weights[0] = firstWeight;
  17. // 权重值总和
  18. int totalWeight = firstWeight;
  19. // 对整个invoker列表进行权重,除第一个外
  20. for (int i = 1; i < length; i++) {
  21. int weight = getWeight(invokers.get(i), invocation);
  22. // 将权重完的值写到对应invoker权重数组中
  23. weights[i] = weight;
  24. // 累加
  25. totalWeight += weight;
  26. // 看当前Invoker是否和第一个权重相同
  27. if (sameWeight && weight != firstWeight) {
  28. sameWeight = false;
  29. }
  30. }
  31. // 如果每个invoker的权重都不一样
  32. if (totalWeight > 0 && !sameWeight) {
  33. // 线程安全的随机数生成器
  34. // 从权重总和中生成一个随机数
  35. int offset = ThreadLocalRandom.current().nextInt(totalWeight);
  36. // 遍历参与权重的invoker列表
  37. for (int i = 0; i < length; i++) {
  38. // 生成的随机数 - 当前循环的invoker(主机) = 随机数
  39. // 如果随机数 小于 0 那本次的负载均衡选择出的就是这个invoker(主机)
  40. // 如果不是小于0 那就继续下一次循环, 继续减去下一个invoker(主机)的权重, 直到最后得到的数是 小于 0为止
  41. offset -= weights[i];
  42. if (offset < 0) {
  43. return invokers.get(i);
  44. }
  45. }
  46. }
  47. // 这里就是所有的invoker中的权重是一致的, 这个时候就进行真正的随机
  48. return invokers.get(ThreadLocalRandom.current().nextInt(length));
  49. }

AbstractLoadBalance.java

  1. /**
  2. * 为当前invoker进行权重
  3. * @param invoker 为当前invoker进行权重
  4. * @param invocation 包含调用信息
  5. * @return weight
  6. */
  7. protected int getWeight(Invoker<?> invoker, Invocation invocation) {
  8. // 从URL中获取当前Invoker设置的权重值
  9. int weight = invoker.getUrl().getMethodParameter(invocation.getMethodName(), WEIGHT_KEY, DEFAULT_WEIGHT);
  10. // 大于0, 则进行权重计算
  11. if (weight > 0) {
  12. // 获取到服务节点的启动时间, 在服务发现的时候 会写入 dubbo框架的版本 dubbo的协议号 当前的时间戳 线程ID
  13. long timestamp = invoker.getUrl().getParameter(REMOTE_TIMESTAMP_KEY, 0L);
  14. if (timestamp > 0L) {
  15. // 当前时间戳 减去 服务启动的时间 = 这个服务节点已经启动多久了
  16. // 取到已经预热时间
  17. int uptime = (int) (System.currentTimeMillis() - timestamp);
  18. // 获取设置的预热时间, 如果不设置默认是10分钟
  19. int warmup = invoker.getUrl().getParameter(WARMUP_KEY, DEFAULT_WARMUP);
  20. if (uptime > 0 && uptime < warmup) {
  21. // 计算预热权重
  22. weight = calculateWarmupWeight(uptime, warmup, weight);
  23. }
  24. }
  25. }
  26. return weight >= 0 ? weight : 0;
  27. }
  28. /**
  29. * Calculate the weight according to the uptime proportion of warmup time
  30. * the new weight will be within 1(inclusive) to weight(inclusive)
  31. *
  32. * @param uptime 已经预热的时候
  33. * @param warmup 用户配置的预热时间
  34. * @param weight 用户配置的权重值
  35. * @return weight which takes warmup into account
  36. */
  37. static int calculateWarmupWeight(int uptime, int warmup, int weight) {
  38. // 这么做的目的是, 服务刚启动的时候需要有个预热的过程,如果一启动就给予100%的流量,则可能会让服务崩溃
  39. // (启动至今时间/给予的预热总时间) X 权重
  40. // 例:
  41. // 假设我们设置A服务的权重是5,让它预热10分钟,则第一分钟的时候,它的权重变为(1/10) X5 = 0.5, 0.5/5 = 0.1,也就是只承担10%的流量;10分钟后
  42. // 权重就变为(10/10) X5 = 5,也就是权重变为设置的100%,承担了所有的流量。
  43. int ww = (int) ((float) uptime / ((float) warmup / (float) weight));
  44. return ww < 1 ? 1 : (ww > weight ? weight : ww);
  45. }

最小活跃度算法

使用方式

  1. <dubbo:reference id="gcService" loadbalance="leastactive" check="false" interface="org.apache.dubbo.gc.GcService"/>

使用场景

  1. 用于服务级别,其适合于提供者主机性能差别不大的场景。根据各个提供者主机当前处理实际情况进行负载均衡。某一台机器处理的请求快,处理完了就又会给这个机器分请求处理。 似于:能力越大 责任越大。

LeastActiveLoadBalance.java

  1. /**
  2. * 最小活跃度
  3. * LeastActiveLoadBalance
  4. * <p>
  5. * Filter the number of invokers with the least number of active calls and count the weights and quantities of these invokers.
  6. * If there is only one invoker, use the invoker directly;
  7. * if there are multiple invokers and the weights are not the same, then random according to the total weight;
  8. * if there are multiple invokers and the same weight, then randomly called.
  9. */
  10. public class LeastActiveLoadBalance extends AbstractLoadBalance {
  11. public static final String NAME = "leastactive";
  12. @Override
  13. protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
  14. // 当前主机列表
  15. int length = invokers.size();
  16. // 主机初始活跃度
  17. int leastActive = -1;
  18. // 具有最小活跃度invoker的数量
  19. int leastCount = 0;
  20. // 该数组中存放的是具有最小活跃度的invoker的索引
  21. int[] leastIndexes = new int[length];
  22. // 该数组存放每个invoker的权重
  23. int[] weights = new int[length];
  24. // 具有最小活跃度的invoker的权重之和
  25. int totalWeight = 0;
  26. // The weight of the first least active invoke
  27. int firstWeight = 0;
  28. // 用于标识 具有最小活跃度的所有invoker的权重是否相同
  29. boolean sameWeight = true;
  30. // 遍历所有invoker,过滤出所有具有最小活跃度的invoker
  31. for (int i = 0; i < length; i++) {
  32. // 拿到当前循环的invoker
  33. Invoker<T> invoker = invokers.get(i);
  34. // 拿到当前invoker方法中的活跃度
  35. int active = RpcStatus.getStatus(invoker.getUrl(), invocation.getMethodName()).getActive();
  36. // 获取权重
  37. int afterWarmup = getWeight(invoker, invocation);
  38. // 记录下当前invoker的权重到数组
  39. weights[i] = afterWarmup;
  40. // 处理找到更小活跃度后的重置
  41. if (leastActive == -1 || active < leastActive) {
  42. // 更新最小活跃度
  43. leastActive = active;
  44. // 重置计数器
  45. leastCount = 1;
  46. // Put the first least active invoker first in leastIndexes
  47. leastIndexes[0] = i;
  48. // 重置权重和
  49. totalWeight = afterWarmup;
  50. // Record the weight the first least active invoker
  51. firstWeight = afterWarmup;
  52. // Each invoke has the same weight (only one invoker here)
  53. sameWeight = true;
  54. // If current invoker's active value equals with leaseActive, then accumulating.
  55. } else if (active == leastActive) {
  56. // 处理找到与最小活跃度相同活跃度的invoker的累计 计数器增一
  57. leastIndexes[leastCount++] = i;
  58. // Accumulate the total weight of the least active invoker
  59. totalWeight += afterWarmup;
  60. // If every invoker has the same weight?
  61. if (sameWeight && i > 0
  62. && afterWarmup != firstWeight) {
  63. sameWeight = false;
  64. }
  65. }
  66. }
  67. // 若具有最小活跃度的invoker就一个,则直接返回这个即可
  68. if (leastCount == 1) {
  69. // If we got exactly one invoker having the least active value, return this invoker directly.
  70. return invokers.get(leastIndexes[0]);
  71. }
  72. if (!sameWeight && totalWeight > 0) {
  73. // If (not every invoker has the same weight & at least one invoker's weight>0), select randomly based on
  74. // totalWeight.
  75. int offsetWeight = ThreadLocalRandom.current().nextInt(totalWeight);
  76. // Return a invoker based on the random value.
  77. for (int i = 0; i < leastCount; i++) {
  78. int leastIndex = leastIndexes[i];
  79. offsetWeight -= weights[leastIndex];
  80. if (offsetWeight < 0) {
  81. return invokers.get(leastIndex);
  82. }
  83. }
  84. }
  85. // If all invokers have the same weight value or totalWeight=0, return evenly.
  86. return invokers.get(leastIndexes[ThreadLocalRandom.current().nextInt(leastCount)]);
  87. }

轮询算法

使用方式

  1. <!-- 该算法是针对方法使用 -->
  2. <dubbo:reference id="gcService" check="false" interface="org.apache.dubbo.gc.GcService">
  3. <dubbo:method name="getGCInfo" loadbalance="leastactive"/>
  4. </dubbo:reference>

使用场景

  1. 用于方法级别,其适合于某服务中包含多个方法,其中某个方法属于高消耗方法(消耗系统资源或耗时)。 若对于该方法的请求突然再现高并发,此时若采用服务级别的负载均衡,则可能会出现问题: 某时刻某个或某些提供者刚处理完毕一批请求,此时它们的负载较小。而此时恰好对这个高消耗的方法的高并发请求到达。这时可能会一次性将大量的这个高消耗请求分配给这些负载较小的提供者,可能会导致这些提供者直接崩溃。

算法详述

现假设有 A B C D E 五台主机,其初始的主机权重分别是 3 5 7 4 9。 轮询权重初始都是0。总共执行6次调用的轮询选出的主机如下图:

14.Dubbo负载均衡源码阅读 - 图6

  1. public class RoundRobinLoadBalance extends AbstractLoadBalance {
  2. public static final String NAME = "roundrobin";
  3. // 回收期,默认60秒
  4. // 若某个invoker的轮询权重当前值“一直”没有变化,
  5. // 则说明每次轮询时都没有其对应的这个invoker,
  6. // 说明这个invoker挂了,需要将其从缓存map中清除。
  7. // 这个“一直”就是这里的 回收期
  8. private static final int RECYCLE_PERIOD = 60000;
  9. // 轮询权重
  10. protected static class WeightedRoundRobin {
  11. // 主机权重
  12. private int weight;
  13. // 轮询权重当前值
  14. private AtomicLong current = new AtomicLong(0);
  15. // 记录轮询权重当前值的增重时间戳
  16. private long lastUpdate;
  17. // 获取主机权重
  18. public int getWeight() {
  19. return weight;
  20. }
  21. // 初始化主机权重
  22. public void setWeight(int weight) {
  23. this.weight = weight;
  24. current.set(0); // 将轮询权重当前值归0
  25. }
  26. // 轮询权重当前值增重,每次增重一个主机权重
  27. public long increaseCurrent() {
  28. return current.addAndGet(weight);
  29. }
  30. // 轮询权重当前值减重,每次增重一个所有主机权重之和
  31. public void sel(int total) {
  32. current.addAndGet(-1 * total);
  33. }
  34. // 获取最后的增重时间戳
  35. public long getLastUpdate() {
  36. return lastUpdate;
  37. }
  38. // 更新最后的增重时间戳
  39. public void setLastUpdate(long lastUpdate) {
  40. this.lastUpdate = lastUpdate;
  41. }
  42. }
  43. // 这是一个双层map,
  44. // 外层map的key是全限定性方法名,value是内层map
  45. // 内层map的key为一个invoker的url,其就代表了一个invoker,所以我们就可以将其直接视为invoker
  46. // 内层map的value为轮询权重实例
  47. // 这个内层map与其对应的外层map的key间的关系是,内层map可以提供外层map的key(方法)的服务
  48. private ConcurrentMap<String, ConcurrentMap<String, WeightedRoundRobin>> methodWeightMap = new ConcurrentHashMap<String, ConcurrentMap<String, WeightedRoundRobin>>();
  49. // 更新锁,其值为false,表示锁是打开的
  50. private AtomicBoolean updateLock = new AtomicBoolean();
  51. /**
  52. * get invoker addr list cached for specified invocation
  53. * <p>
  54. * <b>for unit test only</b>
  55. *
  56. * @param invokers
  57. * @param invocation
  58. * @return
  59. */
  60. protected <T> Collection<String> getInvokerAddrList(List<Invoker<T>> invokers, Invocation invocation) {
  61. String key = invokers.get(0).getUrl().getServiceKey() + "." + invocation.getMethodName();
  62. Map<String, WeightedRoundRobin> map = methodWeightMap.get(key);
  63. if (map != null) {
  64. return map.keySet();
  65. }
  66. return null;
  67. }
  68. @Override
  69. protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
  70. // 获取当前RPC调用的方法的全限定性方法名
  71. String key = invokers.get(0).getUrl().getServiceKey() + "." + invocation.getMethodName();
  72. // 从缓存Map中获取当前调用方法所对应的所有invoker及其对应的轮询权重,即内层map
  73. ConcurrentMap<String, WeightedRoundRobin> map = methodWeightMap.get(key);
  74. // 若这个内层map为null,说明要么没有这个方法,要么真的是这个map为null
  75. // 此时创建一个内层map放入到缓存Map中
  76. if (map == null) {
  77. methodWeightMap.putIfAbsent(key, new ConcurrentHashMap<String, WeightedRoundRobin>());
  78. map = methodWeightMap.get(key);
  79. }
  80. int totalWeight = 0;
  81. // 记录本轮循环中轮询权重当前值的最大值
  82. long maxCurrent = Long.MIN_VALUE;
  83. // 当前时间
  84. long now = System.currentTimeMillis();
  85. // 记录最终被选择出的invoker及其对应的轮询权重实例
  86. Invoker<T> selectedInvoker = null;
  87. WeightedRoundRobin selectedWRR = null;
  88. // 遍历所有invoker
  89. for (Invoker<T> invoker : invokers) {
  90. // 获取当前遍历invoker的url,即内层map的key,格式 dubbo://ip:port/业务接口名
  91. String identifyString = invoker.getUrl().toIdentityString();
  92. // 从缓存中获取当前invoker对应的轮询权重实例
  93. WeightedRoundRobin weightedRoundRobin = map.get(identifyString);
  94. // 获取当前invoker的主机权重
  95. int weight = getWeight(invoker, invocation);
  96. // 若当前invoker对应的轮询权重实例为null,则创建一个新的,初始化后再写入到缓存map
  97. if (weightedRoundRobin == null) {
  98. weightedRoundRobin = new WeightedRoundRobin();
  99. weightedRoundRobin.setWeight(weight);
  100. map.putIfAbsent(identifyString, weightedRoundRobin);
  101. }
  102. // 什么时候主机权重会发生变化?warmup过程中的主机权重
  103. // 会随着时间的推移,越来越接近weight设置值
  104. if (weight != weightedRoundRobin.getWeight()) {
  105. //weight changed
  106. // 更新当前轮询权重实例的主机权重。注意,此时也会将轮询权重当前值归0
  107. weightedRoundRobin.setWeight(weight);
  108. }
  109. // 为当前invoker的轮询权重当前值增重
  110. long cur = weightedRoundRobin.increaseCurrent();
  111. // 记录本次增重时间戳
  112. weightedRoundRobin.setLastUpdate(now);
  113. // 若当前轮询权重当前值比当前记录的最大current还大,则记录下这个值及invoker
  114. if (cur > maxCurrent) {
  115. // 更新最大当前值
  116. maxCurrent = cur;
  117. selectedInvoker = invoker;
  118. selectedWRR = weightedRoundRobin;
  119. }
  120. // 计算主机权重total
  121. totalWeight += weight;
  122. } // end-for
  123. // 若updateLock为false(即更新锁是打开状态),
  124. // 且当前所有可用的invoker数量与缓存中invoker的数量不相同,则进行如下处理
  125. // 问题:这个“不相同”的情况有几种可能?
  126. // 1)invokers.size() > map.size()
  127. // 2)invokers.size() < map.size()
  128. // 分析:
  129. // 1> 若有新增的invoker,则经过前面的for,已经会为这些新增invoker创建相应的轮询实例,
  130. // 将其其放入到了缓存map中。所以对于这种有新增invoker的情况,代码走到这里,其invokers的
  131. // 数量也是与map的size()相同的。故,第1)种情况不可能出现
  132. // 2> 第2)种情况描述的是什么场景?有invoker出现了宕机的情况
  133. if (!updateLock.get() && invokers.size() != map.size()) {
  134. // 上锁
  135. if (updateLock.compareAndSet(false, true)) {
  136. try {
  137. // copy -> modify -> update reference ==> 目的是为了“迭代稳定性”
  138. // 新建一个map
  139. ConcurrentMap<String, WeightedRoundRobin> newMap = new ConcurrentHashMap<String, WeightedRoundRobin>();
  140. // 使用老map初始化新map
  141. newMap.putAll(map);
  142. // 迭代新map
  143. Iterator<Entry<String, WeightedRoundRobin>> it = newMap.entrySet().iterator();
  144. while (it.hasNext()) {
  145. Entry<String, WeightedRoundRobin> item = it.next();
  146. // item.getValue().getLastUpdate() 获取当前迭代元素的最后增重时间戳
  147. // now - item.getValue().getLastUpdate() 当前迭代元素已经有多久没有更新时间戳了
  148. // if()条件用于判断停更时长是否超过了 回收期
  149. // 若超过了,则说明当前迭代invoker已经挂了,需要从map中删除
  150. if (now - item.getValue().getLastUpdate() > RECYCLE_PERIOD) {
  151. it.remove();
  152. }
  153. }
  154. // 将更新过的新map替换掉缓存Map中的老map
  155. methodWeightMap.put(key, newMap);
  156. } finally {
  157. // 解锁
  158. updateLock.set(false);
  159. }
  160. }
  161. }
  162. // 若用于记录轮询权重最大的invoker的变量selectedInvoker不为null,则返回这个invoker
  163. // 但是在返回之前,先让其当前值变为最小
  164. if (selectedInvoker != null) {
  165. // 轮询权重当前值减重变为最小
  166. selectedWRR.sel(totalWeight);
  167. return selectedInvoker;
  168. }
  169. // should not happen here
  170. return invokers.get(0);
  171. }

一致性Hash算法

使用方式

  1. <!-- 该算法针对 方法-参数使用 -->
  2. <dubbo:reference id="gcService" check="false" interface="org.apache.dubbo.gc.GcService">
  3. <dubbo:method name="getGCInfo">
  4. <!-- 对该两个方法的参数进行hash -->
  5. <dubbo:parameter key="hash.arguments" value="1,2" />
  6. <!-- 虚拟主机的数量,用于进行hahs计算 -->
  7. <dubbo:parameter key="hash.nodes" value="160" />
  8. </dubbo:method>
  9. </dubbo:reference>

使用场景

  1. 用于**方法参数**级别,其应用场景是,对于某些方法,其参数选择范围较小,即参数值相对较固定。使用该算 法,可以使对相同方法的相同参数请求,被负载均衡到相同的提供者。这样就可以充分地利用提供者的缓存,从而达到高性能。

ConsistentHashLoadBalance.java

  1. public class ConsistentHashLoadBalance extends AbstractLoadBalance {
  2. public static final String NAME = "consistenthash";
  3. /**
  4. * Hash nodes name
  5. */
  6. public static final String HASH_NODES = "hash.nodes";
  7. /**
  8. * Hash arguments name
  9. */
  10. public static final String HASH_ARGUMENTS = "hash.arguments";
  11. private final ConcurrentMap<String, ConsistentHashSelector<?>> selectors = new ConcurrentHashMap<String, ConsistentHashSelector<?>>();
  12. @SuppressWarnings("unchecked")
  13. @Override
  14. protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
  15. // 获取调用的方法名称
  16. String methodName = RpcUtils.getMethodName(invocation);
  17. // 全限定方法名
  18. String key = invokers.get(0).getUrl().getServiceKey() + "." + methodName;
  19. // 计算出这个列表的hash值, 用于构建selector选择器
  20. int identityHashCode = System.identityHashCode(invokers);
  21. ConsistentHashSelector<T> selector = (ConsistentHashSelector<T>) selectors.get(key);
  22. // 当前选择器是空的, 或者当前列表算出的hash值和缓存的hash不匹配, 则将当前的hash加入到缓存
  23. if (selector == null || selector.identityHashCode != identityHashCode) {
  24. selectors.put(key, new ConsistentHashSelector<T>(invokers, methodName, identityHashCode));
  25. selector = (ConsistentHashSelector<T>) selectors.get(key);
  26. }
  27. // 使用selector根据调用信息进行选择
  28. return selector.select(invocation);
  29. }
  30. private static final class ConsistentHashSelector<T> {
  31. private final TreeMap<Long, Invoker<T>> virtualInvokers;
  32. private final int replicaNumber;
  33. private final int identityHashCode;
  34. private final int[] argumentIndex;
  35. ConsistentHashSelector(List<Invoker<T>> invokers, String methodName, int identityHashCode) {
  36. // 创建一个map用于存放虚拟invoker
  37. // 其key为虚拟invoker(其本质就是一个hash值)
  38. // 其Value为invoker
  39. this.virtualInvokers = new TreeMap<Long, Invoker<T>>();
  40. // 整个invoker列表的hash
  41. this.identityHashCode = identityHashCode;
  42. URL url = invokers.get(0).getUrl();
  43. // 获取hash.nodes属性值,即为每个物理invoker创建的虚拟invoker的数量,默认160
  44. this.replicaNumber = url.getMethodParameter(methodName, HASH_NODES, 160);
  45. // 获取hash.arguments属性值,并使用逗号(,)进行分隔. 该值是用户配置(这个配置值只能是整数数字)
  46. String[] index = COMMA_SPLIT_PATTERN.split(url.getMethodParameter(methodName, HASH_ARGUMENTS, "0"));
  47. // 用户配置了几个参数(解析为长度)
  48. argumentIndex = new int[index.length];
  49. // 并对这些长度逐个取值
  50. for (int i = 0; i < index.length; i++) {
  51. argumentIndex[i] = Integer.parseInt(index[i]);
  52. }
  53. // 开始遍历invoker列表
  54. for (Invoker<T> invoker : invokers) {
  55. // 获取物理invoker的地址 ip:port
  56. String address = invoker.getUrl().getAddress();
  57. for (int i = 0; i < replicaNumber / 4; i++) {
  58. // 使用md5算法生成一个128位的摘要
  59. // 生成一个hash值需要使用一个32位的二进制数,
  60. // 所以一个digest可以生成4个hash,将这个digest分为4段:
  61. // 0-31, 32-63, 64-95, 96-127
  62. byte[] digest = md5(address + i);
  63. // 使用digest的每一段生成一个hash
  64. for (int h = 0; h < 4; h++) {
  65. // 使用一个32位的二进制数生成一个hash,
  66. // 这个hash就代表了一个虚拟invoker
  67. long m = hash(digest, h);
  68. // 将这个hash(虚拟invoker)作为key,
  69. // 物理invoker作为value,写入到map
  70. virtualInvokers.put(m, invoker);
  71. }
  72. }
  73. }
  74. }
  75. public Invoker<T> select(Invocation invocation) {
  76. // 将指定的实参值进行字符串拼接
  77. String key = toKey(invocation.getArguments());
  78. // 根据这个key计算出摘要
  79. byte[] digest = md5(key);
  80. // 使用这个digest的前32位(0-31)计算出一个hash,
  81. // 然后使用这个hash做选择
  82. return selectForKey(hash(digest, 0));
  83. }
  84. private String toKey(Object[] args) {
  85. StringBuilder buf = new StringBuilder();
  86. // 遍历argumentIndex的每一个元素,这些元素是RPC调用方法的实参的索引
  87. for (int i : argumentIndex) {
  88. // 若这个遍历的索引值在有效范围内,则将这个实参拼接
  89. if (i >= 0 && i < args.length) {
  90. buf.append(args[i]);
  91. }
  92. }
  93. return buf.toString();
  94. }
  95. private Invoker<T> selectForKey(long hash) {
  96. // 选择出一个虚拟invoker的entry
  97. // 选择比当前指定hash值大的最小的虚拟invoker(hash值),若不存在,则返回null
  98. Map.Entry<Long, Invoker<T>> entry = virtualInvokers.ceilingEntry(hash);
  99. // 若这个entry为null,则选择第一个虚拟invoker的entry
  100. if (entry == null) {
  101. entry = virtualInvokers.firstEntry();
  102. }
  103. // 返回选择的虚拟invoker对应的物理invoker
  104. return entry.getValue();
  105. }
  106. private long hash(byte[] digest, int number) {
  107. return (((long) (digest[3 + number * 4] & 0xFF) << 24)
  108. | ((long) (digest[2 + number * 4] & 0xFF) << 16)
  109. | ((long) (digest[1 + number * 4] & 0xFF) << 8)
  110. | (digest[number * 4] & 0xFF))
  111. & 0xFFFFFFFFL;
  112. }
  113. private byte[] md5(String value) {
  114. MessageDigest md5;
  115. try {
  116. md5 = MessageDigest.getInstance("MD5");
  117. } catch (NoSuchAlgorithmException e) {
  118. throw new IllegalStateException(e.getMessage(), e);
  119. }
  120. md5.reset();
  121. byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
  122. md5.update(bytes);
  123. return md5.digest();
  124. }
  125. }
  126. }