谈谈Dubbo负载均衡是如何实现的?

开源
在一个截面上碰撞的概率高,但调用量越大分布越均匀,而且按概率使用权重后也比较均匀,有利于动态调整提供者权重。

 [[276413]]

 

谈谈dubbo负载均衡是如何实现的?

 

 

dubbo的负载均衡全部由AbstractLoadBalance的子类来实现

RandomLoadBalance 随机

在一个截面上碰撞的概率高,但调用量越大分布越均匀,而且按概率使用权重后也比较均匀,有利于动态调整提供者权重。

  • 获取invoker的数量
  • 获取第一个invoker的权重,并复制给firstWeight
  • 循环invoker集合,把它们的权重全部相加,并复制给totalWeight,如果权重不相等,那么sameWeight为false
  • 如果invoker集合的权重并不是全部相等的,那么获取一个随机数在1到totalWeight之间,赋值给offset属性
  • 循环遍历invoker集合,获取权重并与offset相减,当offset减到小于零,那么就返回这个inovker
  • 如果权重相等,那么直接在invoker集合里面取一个随机数返回
  1. @Override 
  2.  protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) { 
  3.  int length = invokers.size(); // Number of invokers 
  4.  boolean sameWeight = true; // Every invoker has the same weight? 
  5.  int firstWeight = getWeight(invokers.get(0), invocation); 
  6.  int totalWeight = firstWeight; // The sum of weights 
  7.  for (int i = 1; i < length; i++) { 
  8.  int weight = getWeight(invokers.get(i), invocation); 
  9.  totalWeight += weight; // Sum 
  10.  if (sameWeight && weight != firstWeight) { 
  11.  sameWeight = false
  12.  } 
  13.  } 
  14.  if (totalWeight > 0 && !sameWeight) { 
  15.  // If (not every invoker has the same weight & at least one invoker's weight>0), select randomly based on totalWeight. 
  16.  int offset = ThreadLocalRandom.current().nextInt(totalWeight); 
  17.  // Return a invoker based on the random value. 
  18.  for (int i = 0; i < length; i++) { 
  19.  offset -= getWeight(invokers.get(i), invocation); 
  20.  if (offset < 0) { 
  21.  return invokers.get(i); 
  22.  } 
  23.  } 
  24.  } 
  25.  // If all invokers have the same weight value or totalWeight=0, return evenly. 
  26.  return invokers.get(ThreadLocalRandom.current().nextInt(length)); 
  27.  } 

RoundRobinLoadBalance 轮询

存在慢的提供者累积请求的问题,比如:第二台机器很慢,但没挂,当请求调到第二台时就卡在那,久而久之,所有请求都卡在调到第二台上。

在老的版本上,dubbo会求出最大权重和最小权重,如果权重相等,那么就直接按取模的方式,每次取完后值加一;如果权重不相等,顺序根据权重分配。

在新的版本上,对这个类进行了重构。

  1. 从methodWeightMap这个实例中根据ServiceKey+MethodName的方式获取里面的一个map实例,如果没有则说明第一次进到该方法,则实例化一个放入到methodWeightMap中,并把获取到的实例命名为map
  2. 遍历所有的invokers
  3. 拿到当前的invoker的identifyString作为key,去map里获取weightedRoundRobin实例,如果map里没有则添加一个
  4. 如果weightedRoundRobin的权重和当前invoker的权重不同,说明权重变了,需要重新设置
  5. 获取当前invoker所对应的weightedRoundRobin实例中的current,并加上当前invoker的权重
  6. 设置weightedRoundRobin最后的更新时间
  7. maxCurrent一开始是设置的0,如果当前的weightedRoundRobin的current值大于maxCurrent则进行赋值
  8. 遍历完后会得到最大的权重的invoker的selectedInvoker和这个invoker所对应的weightedRoundRobin赋值给了selectedWRR,还有权重之和totalWeight
  9. 然后把selectedWRR里的current属性减去totalWeight,并返回selectedInvoker

这样看显然是不够清晰的,我们来举个例子:

  1. 假定有3台dubbo provider: 
  2. 10.0.0.1:20884, weight=2 
  3. 10.0.0.1:20886, weight=3 
  4. 10.0.0.1:20888, weight=4 
  5. totalWeight=9; 
  6. 那么第一次调用的时候: 
  7. 10.0.0.1:20884, weight=2 selectedWRR -> current = 2 
  8. 10.0.0.1:20886, weight=3 selectedWRR -> current = 3 
  9. 10.0.0.1:20888, weight=4 selectedWRR -> current = 4 
  10.   
  11. selectedInvoker-> 10.0.0.1:20888  
  12. 调用 selectedWRR.sel(totalWeight);  
  13. 10.0.0.1:20888, weight=4 selectedWRR -> current = -5 
  14. 返回10.0.0.1:20888这个实例 
  15. 那么第二次调用的时候: 
  16. 10.0.0.1:20884, weight=2 selectedWRR -> current = 4 
  17. 10.0.0.1:20886, weight=3 selectedWRR -> current = 6 
  18. 10.0.0.1:20888, weight=4 selectedWRR -> current = -1 
  19. selectedInvoker-> 10.0.0.1:20886  
  20. 调用 selectedWRR.sel(totalWeight);  
  21. 10.0.0.1:20886 , weight=4 selectedWRR -> current = -3 
  22. 返回10.0.0.1:20886这个实例 
  23. 那么第三次调用的时候: 
  24. 10.0.0.1:20884, weight=2 selectedWRR -> current = 6 
  25. 10.0.0.1:20886, weight=3 selectedWRR -> current = 0 
  26. 10.0.0.1:20888, weight=4 selectedWRR -> current = 3 
  27. selectedInvoker-> 10.0.0.1:20884 
  28. 调用 selectedWRR.sel(totalWeight);  
  29. 10.0.0.1:20884, weight=2 selectedWRR -> current = -3 
  30. 返回10.0.0.1:20884这个实例 
  31.  protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) { 
  32.  String key = invokers.get(0).getUrl().getServiceKey() + "." + invocation.getMethodName(); 
  33.  ConcurrentMap<String, WeightedRoundRobin> map = methodWeightMap.get(key); 
  34.  if (map == null) { 
  35.  methodWeightMap.putIfAbsent(key, new ConcurrentHashMap<String, WeightedRoundRobin>()); 
  36.  map = methodWeightMap.get(key); 
  37.  } 
  38.  int totalWeight = 0; 
  39.  long maxCurrent = Long.MIN_VALUE; 
  40.  long now = System.currentTimeMillis(); 
  41.  Invoker<T> selectedInvoker = null
  42.  WeightedRoundRobin selectedWRR = null
  43.  for (Invoker<T> invoker : invokers) { 
  44.  String identifyString = invoker.getUrl().toIdentityString(); 
  45.  WeightedRoundRobin weightedRoundRobin = map.get(identifyString); 
  46.  int weight = getWeight(invoker, invocation); 
  47.  if (weight < 0) { 
  48.  weight = 0; 
  49.  } 
  50.  if (weightedRoundRobin == null) { 
  51.  weightedRoundRobin = new WeightedRoundRobin(); 
  52.  weightedRoundRobin.setWeight(weight); 
  53.  map.putIfAbsent(identifyString, weightedRoundRobin); 
  54.  weightedRoundRobin = map.get(identifyString); 
  55.  } 
  56.  if (weight != weightedRoundRobin.getWeight()) { 
  57.  //weight changed 
  58.  weightedRoundRobin.setWeight(weight); 
  59.  } 
  60.  long cur = weightedRoundRobin.increaseCurrent(); 
  61.  weightedRoundRobin.setLastUpdate(now); 
  62.  if (cur > maxCurrent) { 
  63.  maxCurrent = cur; 
  64.  selectedInvoker = invoker; 
  65.  selectedWRR = weightedRoundRobin; 
  66.  } 
  67.  totalWeight += weight; 
  68.  } 
  69.  if (!updateLock.get() && invokers.size() != map.size()) { 
  70.  if (updateLock.compareAndSet(falsetrue)) { 
  71.  try { 
  72.  // copy -> modify -> update reference 
  73.  ConcurrentMap<String, WeightedRoundRobin> newMap = new ConcurrentHashMap<String, WeightedRoundRobin>(); 
  74.  newMap.putAll(map); 
  75.  Iterator<Entry<String, WeightedRoundRobin>> it = newMap.entrySet().iterator(); 
  76.  while (it.hasNext()) { 
  77.  Entry<String, WeightedRoundRobin> item = it.next(); 
  78.  if (now - item.getValue().getLastUpdate() > RECYCLE_PERIOD) { 
  79.  it.remove(); 
  80.  } 
  81.  } 
  82.  methodWeightMap.put(key, newMap); 
  83.  } finally { 
  84.  updateLock.set(false); 
  85.  } 
  86.  } 
  87.  } 
  88.  if (selectedInvoker != null) { 
  89.  selectedWRR.sel(totalWeight); 
  90.  return selectedInvoker; 
  91.  } 
  92.  // should not happen here 
  93.  return invokers.get(0); 
  94.  } 

LeastActiveLoadBalance 最少活跃调用数

使慢的提供者收到更少请求,因为越慢的提供者的调用前后计数差会越大。

  1. 遍历所有的invoker
  2. 获取当前invoker的活跃数,调用的是RpcStatus的getStatus方法,过滤器里面会记录每个方法的活跃数
  3. 获取当前invoker的权重
  4. 如果是第一次进来或者是当前invoker的活跃数比最小的活跃数还小
  5. 那么把leastActive设置为当前invoker的活跃数,设置leastCount为1,leastIndexes数组的第一个位置设置为1,记录一下totalWeight和firstWeight
  6. 如果不满足第4点的条件,那么判断当前invoker的活跃数和最小的活跃数是否相等
  7. 如果满足第6点,那么把当前的权重加入到totalWeight中,并把leastIndexes数组中记录一下最小活跃数相同的下标;再看一下是否所有的权重相同
  8. 如果invoker集合中只有一个invoker活跃数是最小的,那么直接返回
  9. 如果权重不相等,随机权重后,判断在哪个 Invoker 的权重区间中
  10. 权重相等,直接随机选择 Invoker 即可
  1. 最小活跃数算法实现: 
  2. 假定有3台dubbo provider: 
  3. 10.0.0.1:20884, weight=2,active=2 
  4. 10.0.0.1:20886, weight=3,active=4 
  5. 10.0.0.1:20888, weight=4,active=3 
  6. active=2最小,且只有一个2,所以选择10.0.0.1:20884 
  7. 假定有3台dubbo provider: 
  8. 10.0.0.1:20884, weight=2,active=2 
  9. 10.0.0.1:20886, weight=3,active=2 
  10. 10.0.0.1:20888, weight=4,active=3 
  11. active=2最小,且有2个,所以从[10.0.0.1:20884,10.0.0.1:20886 ]中选择; 
  12. 接下来的算法与随机算法类似: 
  13. 假设offset=1(即random.nextInt(5)=1) 
  14. 1-2=-1<0?是,所以选中 10.0.0.1:20884, weight=2 
  15. 假设offset=4(即random.nextInt(5)=4) 
  16. 4-2=2<0?否,这时候offset=2, 2-3<0?是,所以选中 10.0.0.1:20886, weight=3 
  17.  1: public class LeastActiveLoadBalance extends AbstractLoadBalance { 
  18.  2:  
  19.  3: public static final String NAME = "leastactive"
  20.  4:  
  21.  5: private final Random random = new Random(); 
  22.  6:  
  23.  7: @Override 
  24.  8: protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) { 
  25.  9: int length = invokers.size(); // 总个数 
  26. 10: int leastActive = -1; // 最小的活跃数 
  27. 11: int leastCount = 0; // 相同最小活跃数的个数 
  28. 12: int[] leastIndexes = new int[length]; // 相同最小活跃数的下标 
  29. 13: int totalWeight = 0; // 总权重 
  30. 14: int firstWeight = 0; // 第一个权重,用于于计算是否相同 
  31. 15: boolean sameWeight = true; // 是否所有权重相同 
  32. 16: // 计算获得相同最小活跃数的数组和个数 
  33. 17: for (int i = 0; i < length; i++) { 
  34. 18: Invoker<T> invoker = invokers.get(i); 
  35. 19: int active = RpcStatus.getStatus(invoker.getUrl(), invocation.getMethodName()).getActive(); // 活跃数 
  36. 20: int weight = invoker.getUrl().getMethodParameter(invocation.getMethodName(), Constants.WEIGHT_KEY, Constants.DEFAULT_WEIGHT); // 权重 
  37. 21: if (leastActive == -1 || active < leastActive) { // 发现更小的活跃数,重新开始 
  38. 22: leastActive = active; // 记录最小活跃数 
  39. 23: leastCount = 1; // 重新统计相同最小活跃数的个数 
  40. 24: leastIndexes[0] = i; // 重新记录最小活跃数下标 
  41. 25: totalWeight = weight; // 重新累计总权重 
  42. 26: firstWeight = weight; // 记录第一个权重 
  43. 27: sameWeight = true; // 还原权重相同标识 
  44. 28: } else if (active == leastActive) { // 累计相同最小的活跃数 
  45. 29: leastIndexes[leastCount++] = i; // 累计相同最小活跃数下标 
  46. 30: totalWeight += weight; // 累计总权重 
  47. 31: // 判断所有权重是否一样 
  48. 32: if (sameWeight && weight != firstWeight) { 
  49. 33: sameWeight = false
  50. 34: } 
  51. 35: } 
  52. 36: } 
  53. 37: // assert(leastCount > 0) 
  54. 38: if (leastCount == 1) { 
  55. 39: // 如果只有一个最小则直接返回 
  56. 40: return invokers.get(leastIndexes[0]); 
  57. 41: } 
  58. 42: if (!sameWeight && totalWeight > 0) { 
  59. 43: // 如果权重不相同且权重大于0则按总权重数随机 
  60. 44: int offsetWeight = random.nextInt(totalWeight); 
  61. 45: // 并确定随机值落在哪个片断上 
  62. 46: for (int i = 0; i < leastCount; i++) { 
  63. 47: int leastIndex = leastIndexes[i]; 
  64. 48: offsetWeight -= getWeight(invokers.get(leastIndex), invocation); 
  65. 49: if (offsetWeight <= 0) { 
  66. 50: return invokers.get(leastIndex); 
  67. 51: } 
  68. 52: } 
  69. 53: } 
  70. 54: // 如果权重相同或权重为0则均等随机 
  71. 55: return invokers.get(leastIndexes[random.nextInt(leastCount)]); 
  72. 56: } 
  73. 57:  
  74. 58: } 

ConsistentHashLoadBalance 一致性 Hash

相同参数的请求总是发到同一提供者。当某一台提供者挂时,原本发往该提供者的请求,基于虚拟节点,平摊到其它提供者,不会引起剧烈变动。

  1. 基于 invokers 集合,根据对象内存地址来计算定义哈希值
  2. 获得 ConsistentHashSelector 对象。若为空,或者定义哈希值变更(说明 invokers 集合发生变化),进行创建新的 ConsistentHashSelector 对象
  3. 调用ConsistentHashSelector对象的select方法
  1. 1: public class ConsistentHashLoadBalance extends AbstractLoadBalance { 
  2.  2:  
  3.  3: /** 
  4.  4: * 服务方法与一致性哈希选择器的映射 
  5.  5: * 
  6.  6: * KEY:serviceKey + "." + methodName 
  7.  7: */ 
  8.  8: private final ConcurrentMap<String, ConsistentHashSelector<?>> selectors = new ConcurrentHashMap<String, ConsistentHashSelector<?>>(); 
  9.  9:  
  10. 10: @SuppressWarnings("unchecked"
  11. 11: @Override 
  12. 12: protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) { 
  13. 13: String key = invokers.get(0).getUrl().getServiceKey() + "." + invocation.getMethodName(); 
  14. 14: // 基于 invokers 集合,根据对象内存地址来计算定义哈希值 
  15. 15: int identityHashCode = System.identityHashCode(invokers); 
  16. 16: // 获得 ConsistentHashSelector 对象。若为空,或者定义哈希值变更(说明 invokers 集合发生变化),进行创建新的 ConsistentHashSelector 对象 
  17. 17: ConsistentHashSelector<T> selector = (ConsistentHashSelector<T>) selectors.get(key); 
  18. 18: if (selector == null || selector.identityHashCode != identityHashCode) { 
  19. 19: selectors.put(key, new ConsistentHashSelector<T>(invokers, invocation.getMethodName(), identityHashCode)); 
  20. 20: selector = (ConsistentHashSelector<T>) selectors.get(key); 
  21. 21: } 
  22. 22: return selector.select(invocation); 
  23. 23: } 
  24. 24: } 

ConsistentHashSelector 一致性哈希选择器

ConsistentHashSelector ,是 ConsistentHashLoadBalance 的内部类,一致性哈希选择器,基于 Ketama 算法。

  1. /** 
  2.  * 虚拟节点与 Invoker 的映射关系 
  3.  */ 
  4. private final TreeMap<Long, Invoker<T>> virtualInvokers; 
  5. /** 
  6.  * 每个Invoker 对应的虚拟节点数 
  7.  */ 
  8. private final int replicaNumber; 
  9. /** 
  10.  * 定义哈希值 
  11.  */ 
  12. private final int identityHashCode; 
  13. /** 
  14.  * 取值参数位置数组 
  15.  */ 
  16. private final int[] argumentIndex; 
  17.  1: ConsistentHashSelector(List<Invoker<T>> invokers, String methodName, int identityHashCode) { 
  18.  2: this.virtualInvokers = new TreeMap<Long, Invoker<T>>(); 
  19.  3: // 设置 identityHashCode 
  20.  4: this.identityHashCode = identityHashCode; 
  21.  5: URL url = invokers.get(0).getUrl(); 
  22.  6: // 初始化 replicaNumber 
  23.  7: this.replicaNumber = url.getMethodParameter(methodName, "hash.nodes", 160); 
  24.  8: // 初始化 argumentIndex 
  25.  9: String[] index = Constants.COMMA_SPLIT_PATTERN.split(url.getMethodParameter(methodName, "hash.arguments""0")); 
  26.  10: argumentIndex = new int[index.length]; 
  27.  11: for (int i = 0; i < index.length; i++) { 
  28.  12: argumentIndex[i] = Integer.parseInt(index[i]); 
  29.  13: } 
  30.  14: // 初始化 virtualInvokers 
  31.  15: for (Invoker<T> invoker : invokers) { 
  32.  16: String address = invoker.getUrl().getAddress(); 
  33.  17: // 每四个虚拟结点为一组,为什么这样?下面会说到 
  34.  18: for (int i = 0; i < replicaNumber / 4; i++) { 
  35.  19: // 这组虚拟结点得到惟一名称 
  36.  20: byte[] digest = md5(address + i); 
  37.  21: // Md5是一个16字节长度的数组,将16字节的数组每四个字节一组,分别对应一个虚拟结点,这就是为什么上面把虚拟结点四个划分一组的原因 
  38.  22: for (int h = 0; h < 4; h++) { 
  39.  23: // 对于每四个字节,组成一个long值数值,做为这个虚拟节点的在环中的惟一key 
  40.  24: long m = hash(digest, h); 
  41.  25: virtualInvokers.put(m, invoker); 
  42.  26: } 
  43.  27: } 
  44.  28: } 
  45.  29: } 
  46. public Invoker<T> select(Invocation invocation) { 
  47.  // 基于方法参数,获得 KEY 
  48.  String key = toKey(invocation.getArguments()); 
  49.  // 计算 MD5 值 
  50.  byte[] digest = md5(key); 
  51.  // 计算 KEY 值 
  52.  return selectForKey(hash(digest, 0)); 
  53. private String toKey(Object[] args) { 
  54.  StringBuilder buf = new StringBuilder(); 
  55.  for (int i : argumentIndex) { 
  56.  if (i >= 0 && i < args.length) { 
  57.  buf.append(args[i]); 
  58.  } 
  59.  } 
  60.  return buf.toString(); 
  61. private Invoker<T> selectForKey(long hash) { 
  62.  // 得到大于当前 key 的那个子 Map ,然后从中取出第一个 key ,就是大于且离它最近的那个 key 
  63.  Map.Entry<Long, Invoker<T>> entry = virtualInvokers.tailMap(hash, true).firstEntry(); 
  64.  // 不存在,则取 virtualInvokers 第一个 
  65.  if (entry == null) { 
  66.  entry = virtualInvokers.firstEntry(); 
  67.  } 
  68.  // 存在,则返回 
  69.  return entry.getValue(); 

 

 

责任编辑:武晓燕 来源: 今日头条
相关推荐

2010-05-10 17:52:30

实现负载均衡

2019-06-09 09:13:14

Istio负载均衡架构

2023-02-13 16:39:45

Kubernetes容器负载均衡器

2021-08-23 06:59:22

Nacos负载均衡客户端

2023-10-25 22:23:35

Dubbo路由

2019-11-07 08:49:26

Apache Dubb架构负载均衡

2010-04-20 14:31:29

负载均衡功能

2010-05-10 15:22:57

实现负载均衡

2012-10-19 10:21:07

数据库负载均衡mssqlserver

2010-04-28 12:38:38

负载均衡的概念

2013-12-13 09:55:44

VDI负载均衡

2010-04-22 10:46:40

Lvs负载均衡故障负载均衡器

2010-03-24 10:35:02

Nginx负载均衡器

2011-11-22 21:26:59

pfSense配置Web服务器负载均衡

2010-04-20 10:27:57

什么是负载均衡

2017-07-03 08:08:25

负载均衡分类

2015-09-25 09:56:37

负载均衡

2009-12-18 16:05:03

智能型负载均衡

2013-12-13 09:52:58

VDI服务器负载均衡

2022-04-02 07:52:47

DubboRPC调用动态代理
点赞
收藏

51CTO技术栈公众号