Dubbo源码 - 负载均衡

女爷i 2024-04-08 09:06 180阅读 0赞

前言

负载均衡,英文名称为Load Balance,其含义就是指将负载(工作任务)进行平衡、分摊到多个操作单元上进行运行。

例如:在Dubbo中,同一个服务有多个服务提供者,每个服务提供者所在的机器性能不一致。如果流量均匀分摊,则会导致有些服务提供者负载过高,有些则轻轻松松,导致资源浪费。负载均衡就解决这个问题。

源码

LoadBalance 就是负载均衡的接口,咱们先看看类图

0070d0f34f78adb5e5831dbf3bc6c013.png

Dubbo提供了4中内置的负载均衡实现:

  1. RandomLoadBalance:基于权重随机算法
  2. LeastActiveLoadBalance:基于最少活跃调用数算法
  3. ConsistentHashLoadBalance:基于 hash 一致性算法
  4. RoundRobinLoadBalance:基于加权轮询算法

那么负载均衡是在哪里被用的的呢?

AbstractClusterInvokerselectreselect 方法。

AbstractLoadBalance

抽象类封装了一些公共的逻辑,在看具体实现类之前,我们先看看抽象类AbstractLoadBalance中的方法

  1. public <T> Invoker<T> select(List<Invoker<T>> invokers, URL url, Invocation invocation) {
  2. if (invokers == null || invokers.isEmpty())
  3. return null;
  4. // 如果 invokers 列表中仅有一个 Invoker,直接返回即可,无需进行负载均衡
  5. if (invokers.size() == 1)
  6. return invokers.get(0);
  7. // 调用 doSelect 方法进行负载均衡,该方法为抽象方法,由子类实现
  8. return doSelect(invokers, url, invocation);
  9. }

LoadBalance 接口只有一个方法,那就是 select 方法,这是负载均衡的入口。根据 invoker 数量判断是否需要进行负载均衡。这里的 doSelect 是个抽象方法,由子类实现。

  1. protected int getWeight(Invoker<?> invoker, Invocation invocation) {
  2. int weight = invoker.getUrl().getMethodParameter(invocation.getMethodName(), Constants.WEIGHT_KEY, Constants.DEFAULT_WEIGHT);
  3. if (weight > 0) {
  4. // 获取服务提供者启动时间戳
  5. long timestamp = invoker.getUrl().getParameter(Constants.REMOTE_TIMESTAMP_KEY, 0L);
  6. if (timestamp > 0L) {
  7. // 计算服务提供者运行时长
  8. int uptime = (int) (System.currentTimeMillis() - timestamp);
  9. // 获取服务预热时间,默认为10分钟
  10. int warmup = invoker.getUrl().getParameter(Constants.WARMUP_KEY, Constants.DEFAULT_WARMUP);
  11. // 如果服务运行时间小于预热时间,则重新计算服务权重,即降权
  12. if (uptime > 0 && uptime < warmup) {
  13. // 重新计算服务权重
  14. weight = calculateWarmupWeight(uptime, warmup, weight);
  15. }
  16. }
  17. }
  18. return weight;
  19. }
  20. static int calculateWarmupWeight(int uptime, int warmup, int weight) {
  21. // 计算权重,下面代码逻辑上形似于 (uptime / warmup) * weight。
  22. // 随着服务运行时间 uptime 增大,权重计算值 ww 会慢慢接近配置值 weight
  23. int ww = (int) ((float) uptime / ((float) warmup / (float) weight));
  24. return ww < 1 ? 1 : (ww > weight ? weight : ww);
  25. }

getWeight 是获取权重的方法,默认权重为100,这里有个服务预热的操作,当服务的启动时间小于预热时间,权重会减少,这个权重由 calculateWarmupWeight 方法计算。

预热的目的是让服务启动后“低功率”运行一段时间,使其效率慢慢提升至最佳状态。

以上就是抽象类的全部方法。下面我们看实现类的。

RandomLoadBalance

RandomLoadBalance 是加权随机算法的具体实现,是Dubbo默认的负载均衡策略。

假设我们有一组服务器 servers = [A, B, C],他们对应的权重为 weights = [5, 3, 2],权重总和为10。

4d6c36eaf7f46d22b073a6a401f18bd8.png

我们取一个大于等于0,小于10的随机数,计算随机数落在哪个区间。例如4在A区间,7在B区间。

权重越大,落在该区间的概率就越大。这就是加权随机算法。

下面看具体代码实现

  1. public class RandomLoadBalance extends AbstractLoadBalance {
  2. public static final String NAME = "random";
  3. private final Random random = new Random();
  4. @Override
  5. protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
  6. int length = invokers.size(); // Number of invokers
  7. int totalWeight = 0; // The sum of weights
  8. boolean sameWeight = true; // Every invoker has the same weight?
  9. // 下面这个循环有两个作用,第一是计算总权重 totalWeight,
  10. // 第二是检测每个服务提供者的权重是否相同
  11. for (int i = 0; i < length; i++) {
  12. int weight = getWeight(invokers.get(i), invocation);
  13. totalWeight += weight; // Sum
  14. // 检测当前服务提供者的权重与上一个服务提供者的权重是否相同,
  15. // 不相同的话,则将 sameWeight 置为 false。
  16. if (sameWeight && i > 0
  17. && weight != getWeight(invokers.get(i - 1), invocation)) {
  18. sameWeight = false;
  19. }
  20. }
  21. if (totalWeight > 0 && !sameWeight) {
  22. // 随机获取一个 [0, totalWeight) 区间内的数字
  23. int offset = random.nextInt(totalWeight);
  24. // Return a invoker based on the random value.
  25. // 循环让 offset 数减去服务提供者权重值,当 offset 小于0时,返回相应的 Invoker。
  26. // 举例说明一下,我们有 servers = [A, B, C],weights = [5, 3, 2],offset = 7。
  27. // 第一次循环,offset - 5 = 2 > 0,即 offset > 5,
  28. // 表明其不会落在服务器 A 对应的区间上。
  29. // 第二次循环,offset - 3 = -1 < 0,即 5 < offset < 8,
  30. // 表明其会落在服务器 B 对应的区间上
  31. for (int i = 0; i < length; i++) {
  32. // 让随机值 offset 减去权重值
  33. offset -= getWeight(invokers.get(i), invocation);
  34. if (offset < 0) {
  35. // 返回相应的 Invoker
  36. return invokers.get(i);
  37. }
  38. }
  39. }
  40. // 如果所有服务提供者权重值相同,此时直接随机返回一个即可
  41. return invokers.get(random.nextInt(length));
  42. }
  43. }

如果权重一致,就随机选择一个。如果权重不同,则根据权重分配。

LeastActiveLoadBalance

最小活跃数负载均衡。这个活跃数表示执行中的请求数量。每个服务提供者对应一个活跃数 active。初始情况下,所有服务提供者活跃数均为0。每收到一个请求,活跃数加1,完成请求后则将活跃数减1。

在流量均匀的情况下,活跃数越低的服务提供者,其性能越好。

  1. protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
  2. int length = invokers.size(); // Number of invokers
  3. // 最小的活跃数
  4. int leastActive = -1; // The least active value of all invokers
  5. // 具有相同“最小活跃数”的服务者提供者(以下用 Invoker 代称)数量
  6. int leastCount = 0; // The number of invokers having the same least active value (leastActive)
  7. // leastIndexs 用于记录具有相同“最小活跃数”的 Invoker 在 invokers 列表中的下标信息
  8. int[] leastIndexs = new int[length]; // The index of invokers having the same least active value (leastActive)
  9. int totalWeight = 0; // The sum of with warmup weights
  10. // 第一个最小活跃数的 Invoker 权重值,用于与其他具有相同最小活跃数的 Invoker 的权重进行对比,
  11. // 以检测是否“所有具有相同最小活跃数的 Invoker 的权重”均相等
  12. int firstWeight = 0; // Initial value, used for comparision
  13. boolean sameWeight = true; // Every invoker has the same weight value?
  14. // 遍历 invokers 列表
  15. for (int i = 0; i < length; i++) {
  16. Invoker<T> invoker = invokers.get(i);
  17. // 获取 Invoker 对应的活跃数
  18. int active = RpcStatus.getStatus(invoker.getUrl(), invocation.getMethodName()).getActive(); // Active number
  19. // 获取权重
  20. int afterWarmup = getWeight(invoker, invocation); // Weight
  21. // 发现更小的活跃数,重新开始
  22. if (leastActive == -1 || active < leastActive) { // Restart, when find a invoker having smaller least active value.
  23. // 使用当前活跃数 active 更新最小活跃数 leastActive
  24. leastActive = active; // Record the current least active value
  25. // 更新 leastCount 为 1
  26. leastCount = 1; // Reset leastCount, count again based on current leastCount
  27. // 记录当前下标值到 leastIndexs 中
  28. leastIndexs[0] = i; // Reset
  29. totalWeight = afterWarmup; // Reset
  30. firstWeight = afterWarmup; // Record the weight the first invoker
  31. sameWeight = true; // Reset, every invoker has the same weight value?
  32. // 当前 Invoker 的活跃数 active 与最小活跃数 leastActive 相同
  33. } else if (active == leastActive) { // If current invoker's active value equals with leaseActive, then accumulating.
  34. // 在 leastIndexs 中记录下当前 Invoker 在 invokers 集合中的下标
  35. leastIndexs[leastCount++] = i; // Record index number of this invoker
  36. // 累加权重
  37. totalWeight += afterWarmup; // Add this invoker's weight to totalWeight.
  38. // If every invoker has the same weight?
  39. // 检测当前 Invoker 的权重与 firstWeight 是否相等,
  40. // 不相等则将 sameWeight 置为 false
  41. if (sameWeight && i > 0
  42. && afterWarmup != firstWeight) {
  43. sameWeight = false;
  44. }
  45. }
  46. }
  47. // assert(leastCount > 0)
  48. // 当只有一个 Invoker 具有最小活跃数,此时直接返回该 Invoker 即可
  49. if (leastCount == 1) {
  50. // If we got exactly one invoker having the least active value, return this invoker directly.
  51. return invokers.get(leastIndexs[0]);
  52. }
  53. // 有多个 Invoker 具有相同的最小活跃数,但它们之间的权重不同
  54. if (!sameWeight && totalWeight > 0) {
  55. // If (not every invoker has the same weight & at least one invoker's weight>0), select randomly based on totalWeight.
  56. // 随机生成一个 [0, totalWeight) 之间的数字
  57. int offsetWeight = random.nextInt(totalWeight) + 1;
  58. // Return a invoker based on the random value.
  59. // 循环让随机数减去具有最小活跃数的 Invoker 的权重值,
  60. // 当 offset 小于等于0时,返回相应的 Invoker
  61. for (int i = 0; i < leastCount; i++) {
  62. int leastIndex = leastIndexs[i];
  63. // 获取权重值,并让随机数减去权重值
  64. offsetWeight -= getWeight(invokers.get(leastIndex), invocation);
  65. if (offsetWeight <= 0)
  66. return invokers.get(leastIndex);
  67. }
  68. }
  69. // If all invokers have the same weight value or totalWeight=0, return evenly.
  70. // 如果权重相同或权重为0时,随机返回一个 Invoker
  71. return invokers.get(leastIndexs[random.nextInt(leastCount)]);
  72. }

代码比较多,不过都有注释,耐心看即可。这里大体做了几件事:

  1. 遍历 invokers 集合,找出活跃数最小的 invoker
  2. 如果只有一个 invoker 有最小活跃数,则返回
  3. 如果有多个 invoker 有相同的最小活跃数,则这些 invoker 进行加权随机算法处理(也就是对这几个最小活跃数 invoker 进行 RandomLoadBalance 的逻辑)

这里有个点想扩展说下,就是获取活跃数的方法

RpcStatus.getStatus(invoker.getUrl(), invocation.getMethodName()).getActive();

RpcStatus 记录着当前调用次数、总数、失败数、调用间隔等状态信息。

这些信息,在服务消费者端由 ActiveLimitFilter 记录,在服务提供者端由 ExecuteLimitFilter 记录。也就是,想要拿到正确的活跃数,需要 ActiveLimitFilter 生效才行。

  1. @Activate(group = Constants.CONSUMER, value = Constants.ACTIVES_KEY)
  2. public class ActiveLimitFilter implements Filter

ActiveLimitFilter 生效需要满足两个条件,消费者端以及URL中携带 actives 参数。 actives 可在消费者端或生产者端配置,含义为:每服务消费者每服务每方法最大并发调用数

  1. <dubbo:service interface="com.alibaba.dubbo.demo.DemoService" ref="demoService" registry="remoteRegistry" actives="5" />
  2. <dubbo:reference id="demoService" interface="com.alibaba.dubbo.demo.DemoService" loadbalance="leastactive" actives="5" />

当然,也能给消费者接口指定过滤器的方法来启用 ActiveLimitFilter

  1. <dubbo:reference id="demoService" interface="com.alibaba.dubbo.demo.DemoService" filter="activelimit" />

RoundRobinLoadBalance

RoundRobinLoadBalance是加权轮询负载均衡的实现。加权轮询的原理步骤如下:

假设服务 [A, B, C] 的权重为 [5, 1, 1] ,即总权重为 7, 当前权重currentWeight初始为[0, 0, 0]

  1. 当前权重加上每个服务各自的权重,跳转步骤2

    此时currentWeight为 [0+5, 0+1, 0+1] = [5, 1, 1]

  2. 返回currentWeight中最高的服务,跳转步骤3

    currentWeight为 [5, 1, 1] ,返回服务A

  3. 将第2步中的那个最高权重在currentWeight对应的值减去总权重,跳转步骤4

    currentWeight为 [5 - 7, 1, 1] = [-2, 1, 1]

  4. 重复步骤1

下面的GIF图为了好表示柱状图,所以我将currentWeight初始权重变为10

1ddb278091ff4ba78b2001895a8108c4.gif

经过一定循环次数,最终currentWeight又会回归初始值。而这个循环次数计算如下:

次数 = (最大公约数 / 服务A的权重) + (最大公约数 / 服务B的权重) + …

看完原理,我们继续看源码

  1. protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
  2. // key = 全限定类名 + "." + 方法名,比如 com.xxx.DemoService.sayHello
  3. String key = invokers.get(0).getUrl().getServiceKey() + "." + invocation.getMethodName();
  4. // 获取 url 到 WeightedRoundRobin 映射表,如果为空,则创建一个新的
  5. ConcurrentMap<String, WeightedRoundRobin> map = methodWeightMap.get(key);
  6. if (map == null) {
  7. methodWeightMap.putIfAbsent(key, new ConcurrentHashMap<String, WeightedRoundRobin>());
  8. map = methodWeightMap.get(key);
  9. }
  10. // 权重总和
  11. int totalWeight = 0;
  12. // 最大权重
  13. long maxCurrent = Long.MIN_VALUE;
  14. long now = System.currentTimeMillis();
  15. Invoker<T> selectedInvoker = null;
  16. WeightedRoundRobin selectedWRR = null;
  17. // 下面这个循环主要做了这样几件事情:
  18. // 1. 遍历 Invoker 列表,检测当前 Invoker 是否有
  19. // 相应的 WeightedRoundRobin,没有则创建
  20. // 2. 检测 Invoker 权重是否发生了变化,若变化了,
  21. // 则更新 WeightedRoundRobin 的 weight 字段
  22. // 3. 让 current 字段加上自身权重,等价于 current += weight
  23. // 4. 设置 lastUpdate 字段,即 lastUpdate = now
  24. // 5. 寻找具有最大 current 的 Invoker,以及 Invoker 对应的 WeightedRoundRobin,
  25. // 暂存起来,留作后用
  26. // 6. 计算权重总和
  27. for (Invoker<T> invoker : invokers) {
  28. String identifyString = invoker.getUrl().toIdentityString();
  29. WeightedRoundRobin weightedRoundRobin = map.get(identifyString);
  30. int weight = getWeight(invoker, invocation);
  31. if (weight < 0) {
  32. weight = 0;
  33. }
  34. // 检测当前 Invoker 是否有对应的 WeightedRoundRobin,没有则创建
  35. if (weightedRoundRobin == null) {
  36. weightedRoundRobin = new WeightedRoundRobin();
  37. // 设置 Invoker 权重
  38. weightedRoundRobin.setWeight(weight);
  39. // 存储 url 唯一标识 identifyString 到 weightedRoundRobin 的映射关系
  40. map.putIfAbsent(identifyString, weightedRoundRobin);
  41. weightedRoundRobin = map.get(identifyString);
  42. }
  43. // Invoker 权重不等于 WeightedRoundRobin 中保存的权重,说明权重变化了,此时进行更新
  44. if (weight != weightedRoundRobin.getWeight()) {
  45. //weight changed
  46. weightedRoundRobin.setWeight(weight);
  47. }
  48. // 让 current 加上自身权重,等价于 current += weight
  49. long cur = weightedRoundRobin.increaseCurrent();
  50. // 设置 lastUpdate,表示近期更新过
  51. weightedRoundRobin.setLastUpdate(now);
  52. if (cur > maxCurrent) {
  53. maxCurrent = cur;
  54. // 将具有最大 current 权重的 Invoker 赋值给 selectedInvoker
  55. selectedInvoker = invoker;
  56. // 将 Invoker 对应的 weightedRoundRobin 赋值给 selectedWRR,留作后用
  57. selectedWRR = weightedRoundRobin;
  58. }
  59. // 计算权重总和
  60. totalWeight += weight;
  61. }
  62. // 对 <identifyString, WeightedRoundRobin> 进行检查,过滤掉长时间未被更新的节点。
  63. // 该节点可能挂了,invokers 中不包含该节点,所以该节点的 lastUpdate 长时间无法被更新。
  64. // 若未更新时长超过阈值后,就会被移除掉,默认阈值为60秒。
  65. if (!updateLock.get() && invokers.size() != map.size()) {
  66. if (updateLock.compareAndSet(false, true)) {
  67. try {
  68. // copy -> modify -> update reference
  69. ConcurrentMap<String, WeightedRoundRobin> newMap = new ConcurrentHashMap<String, WeightedRoundRobin>();
  70. // 拷贝
  71. newMap.putAll(map);
  72. // 遍历修改,即移除过期记录
  73. Iterator<Entry<String, WeightedRoundRobin>> it = newMap.entrySet().iterator();
  74. while (it.hasNext()) {
  75. Entry<String, WeightedRoundRobin> item = it.next();
  76. if (now - item.getValue().getLastUpdate() > RECYCLE_PERIOD) {
  77. it.remove();
  78. }
  79. }
  80. // 更新引用
  81. methodWeightMap.put(key, newMap);
  82. } finally {
  83. updateLock.set(false);
  84. }
  85. }
  86. }
  87. if (selectedInvoker != null) {
  88. // 让 current 减去权重总和,等价于 current -= totalWeight
  89. selectedWRR.sel(totalWeight);
  90. // 返回具有最大 current 的 Invoker
  91. return selectedInvoker;
  92. }
  93. // should not happen here
  94. return invokers.get(0);
  95. }

注释写的很详细了,和原理步骤差不多,源码中多个对长时间未更新 invoker 的处理。

ConsistentHashLoadBalance

一致性Hash算法。

其原理简单讲,就是假定有一个圆环,每个服务根据其 hash 值,在圆环上有个位置(如图的cache-1、cache-2等)。当有请求过来的,同样根据请求的 hash 值确定请求的位置,并根据请求的位置去获取最近的下一个服务的位置。如下图:

17b4424f1d8eb44bd5eacf18a578fbd8.png

当请求落在 cache-2 和 cache-3 之间时,下一个最近的是 cache-3,如果 cache-3 服务不可用,那么最近的下个服务就是 cache-4

这时,又引入了一个资源倾斜的问题,那就是大量请求集中在同一个服务中。由于服务在圆环上分布不均,导致大部分请求都落在cache-2中,如下图:

ce70347370bc5b143be7001eac1ec1e7.png

那么该如何处理资源倾斜的问题?引入虚拟节点,就是一个服务有多个多个位置,这样就能使请求更均匀,如下图:

0879a0497bdb7532540d422edd3f3b1e.png

以上就是一致性hash算法的原理。下面讲讲Dubbo的源码

  1. public class ConsistentHashLoadBalance extends AbstractLoadBalance {
  2. private final ConcurrentMap<String, ConsistentHashSelector<?>> selectors = new ConcurrentHashMap<String, ConsistentHashSelector<?>>();
  3. @Override
  4. protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
  5. String methodName = RpcUtils.getMethodName(invocation);
  6. String key = invokers.get(0).getUrl().getServiceKey() + "." + methodName;
  7. // 获取 invokers 原始的 hashcode
  8. int identityHashCode = System.identityHashCode(invokers);
  9. ConsistentHashSelector<T> selector = (ConsistentHashSelector<T>) selectors.get(key);
  10. // 如果 invokers 是一个新的 List 对象,意味着服务提供者数量发生了变化,可能新增也可能减少了。
  11. // 此时 selector.identityHashCode != identityHashCode 条件成立
  12. if (selector == null || selector.identityHashCode != identityHashCode) {
  13. // 创建新的 ConsistentHashSelector
  14. selectors.put(key, new ConsistentHashSelector<T>(invokers, methodName, identityHashCode));
  15. selector = (ConsistentHashSelector<T>) selectors.get(key);
  16. }
  17. // 调用 ConsistentHashSelector 的 select 方法选择 Invoker
  18. return selector.select(invocation);
  19. }
  20. private static final class ConsistentHashSelector<T> {...}
  21. }

doSelect 方法先从缓存获取 selector ,如果缓存没有,则创建并放入缓存。然后调用 selector.select 方法获取 invoker 。所以一致性 hash 的实现,在ConsistentHashSelector中。我们先看其构造方法

  1. ConsistentHashSelector(List<Invoker<T>> invokers, String methodName, int identityHashCode) {
  2. // 可以认为virtualInvokers组成了hash环
  3. this.virtualInvokers = new TreeMap<Long, Invoker<T>>();
  4. this.identityHashCode = identityHashCode;
  5. URL url = invokers.get(0).getUrl();
  6. // 获取虚拟节点数,默认为160
  7. this.replicaNumber = url.getMethodParameter(methodName, "hash.nodes", 160);
  8. // 获取参与 hash 计算的参数下标值,默认对第一个参数进行 hash 运算
  9. String[] index = Constants.COMMA_SPLIT_PATTERN.split(url.getMethodParameter(methodName, "hash.arguments", "0"));
  10. argumentIndex = new int[index.length];
  11. for (int i = 0; i < index.length; i++) {
  12. argumentIndex[i] = Integer.parseInt(index[i]);
  13. }
  14. for (Invoker<T> invoker : invokers) {
  15. String address = invoker.getUrl().getAddress();
  16. for (int i = 0; i < replicaNumber / 4; i++) {
  17. // 对 address + i 进行 md5 运算,得到一个长度为16的字节数组
  18. byte[] digest = md5(address + i);
  19. // 对 digest 部分字节进行4次 hash 运算,得到四个不同的 long 型正整数
  20. for (int h = 0; h < 4; h++) {
  21. // h = 0 时,取 digest 中下标为 0 ~ 3 的4个字节进行位运算
  22. // h = 1 时,取 digest 中下标为 4 ~ 7 的4个字节进行位运算
  23. // h = 2, h = 3 时过程同上
  24. long m = hash(digest, h);
  25. // 将 hash 到 invoker 的映射关系存储到 virtualInvokers 中,
  26. // virtualInvokers 需要提供高效的查询操作,因此选用 TreeMap 作为存储结构
  27. virtualInvokers.put(m, invoker);
  28. }
  29. }
  30. }
  31. }

ConsistentHashSelector的构造方法,主要是计算 invokers 的每一个 invoker 的hash,并将其放入 virtualInvokers 中。从这里可以看到,Dubbo默认的虚拟节点为160个。对比一致性 hash 算法中,virtualInvokers 就是 hash 环,invoker 就是节点。

我们继续看如何从 hash 环中找到最近的节点

  1. public Invoker<T> select(Invocation invocation) {
  2. // 将参数转为 key
  3. String key = toKey(invocation.getArguments());
  4. // 对参数 key 进行 md5 运算
  5. byte[] digest = md5(key);
  6. // 取 digest 数组的前四个字节进行 hash 运算,再将 hash 值传给 selectForKey 方法,
  7. // 寻找合适的 Invoker
  8. return selectForKey(hash(digest, 0));
  9. }
  10. private Invoker<T> selectForKey(long hash) {
  11. // 到 TreeMap 中查找第一个节点值大于或等于当前 hash 的 Invoker
  12. Map.Entry<Long, Invoker<T>> entry = virtualInvokers.tailMap(hash, true).firstEntry();
  13. // 如果 hash 大于 Invoker 在圆环上最大的位置,此时 entry = null,
  14. // 需要将 TreeMap 的头节点赋值给 entry
  15. if (entry == null) {
  16. entry = virtualInvokers.firstEntry();
  17. }
  18. return entry.getValue();
  19. }

选择的过程也很简单,依赖的是 TreeMap 的 tailMap 方法。

总结

本文介绍了Dubbo内置的4中负载均衡实现。至此,Dubbo的集群容错的四个部分,也就是服务目录 Directory、服务路由 Router、集群 Cluster 和负载均衡 LoadBalance 都已全部讲完。

发表评论

表情:
评论列表 (有 0 条评论,180人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Dubbo - 负载均衡

    前言 负载均衡,英文名称为Load Balance,其含义就是指将负载(工作任务)进行平衡、分摊到多个操作单元上进行运行。 例如:在Dubbo中,同一个服务有多个服务提

    相关 Dubbo-负载均衡

    切勿将负载均衡策略写死在代码里,将来我们可以用控制台来进行控制。 负载均衡 在集群负载均衡时,Dubbo 提供了多种均衡策略,缺省为 `random` 随机调