前言
本文基于Dubbo2.6.x版本,中文注释版源码已上传github:xiaoguyu/dubbo
负载均衡,英文名称为Load Balance,其含义就是指将负载(工作任务)进行平衡、分摊到多个操作单元上进行运行。
例如:在Dubbo中,同一个服务有多个服务提供者,每个服务提供者所在的机器性能不一致。如果流量均匀分摊,则会导致有些服务提供者负载过高,有些则轻轻松松,导致资源浪费。负载均衡就解决这个问题。
源码
LoadBalance就是负载均衡的接口,咱们先看看类图

Dubbo提供了4中内置的负载均衡实现:
- RandomLoadBalance:基于权重随机算法
- LeastActiveLoadBalance:基于最少活跃调用数算法
- ConsistentHashLoadBalance:基于 hash 一致性算法
- RoundRobinLoadBalance:基于加权轮询算法
那么负载均衡是在哪里被用的的呢?
AbstractClusterInvoker的select和reselect方法。不熟悉这两个方法的,可以去看《Dubbo集群》
AbstractLoadBalance
抽象类封装了一些公共的逻辑,在看具体实现类之前,我们先看看抽象类AbstractLoadBalance中的方法- public <T> Invoker<T> select(List<Invoker<T>> invokers, URL url, Invocation invocation) {
- if (invokers == null || invokers.isEmpty())
- return null;
- // 如果 invokers 列表中仅有一个 Invoker,直接返回即可,无需进行负载均衡
- if (invokers.size() == 1)
- return invokers.get(0);
- // 调用 doSelect 方法进行负载均衡,该方法为抽象方法,由子类实现
- return doSelect(invokers, url, invocation);
- }
复制代码 LoadBalance接口只有一个方法,那就是 select 方法,这是负载均衡的入口。根据 invoker 数量判断是否需要进行负载均衡。这里的 doSelect 是个抽象方法,由子类实现。- protected int getWeight(Invoker<?> invoker, Invocation invocation) {
- int weight = invoker.getUrl().getMethodParameter(invocation.getMethodName(), Constants.WEIGHT_KEY, Constants.DEFAULT_WEIGHT);
- if (weight > 0) {
- // 获取服务提供者启动时间戳
- long timestamp = invoker.getUrl().getParameter(Constants.REMOTE_TIMESTAMP_KEY, 0L);
- if (timestamp > 0L) {
- // 计算服务提供者运行时长
- int uptime = (int) (System.currentTimeMillis() - timestamp);
- // 获取服务预热时间,默认为10分钟
- int warmup = invoker.getUrl().getParameter(Constants.WARMUP_KEY, Constants.DEFAULT_WARMUP);
- // 如果服务运行时间小于预热时间,则重新计算服务权重,即降权
- if (uptime > 0 && uptime < warmup) {
- // 重新计算服务权重
- weight = calculateWarmupWeight(uptime, warmup, weight);
- }
- }
- }
- return weight;
- }
- static int calculateWarmupWeight(int uptime, int warmup, int weight) {
- // 计算权重,下面代码逻辑上形似于 (uptime / warmup) * weight。
- // 随着服务运行时间 uptime 增大,权重计算值 ww 会慢慢接近配置值 weight
- int ww = (int) ((float) uptime / ((float) warmup / (float) weight));
- return ww < 1 ? 1 : (ww > weight ? weight : ww);
- }
复制代码 getWeight 是获取权重的方法,默认权重为100,这里有个服务预热的操作,当服务的启动时间小于预热时间,权重会减少,这个权重由 calculateWarmupWeight 方法计算。
预热的目的是让服务启动后“低功率”运行一段时间,使其效率慢慢提升至最佳状态。
以上就是抽象类的全部方法。下面我们看实现类的。
RandomLoadBalance
RandomLoadBalance 是加权随机算法的具体实现,是Dubbo默认的负载均衡策略。
假设我们有一组服务器 servers = [A, B, C],他们对应的权重为 weights = [5, 3, 2],权重总和为10。

我们取一个大于等于0,小于10的随机数,计算随机数落在哪个区间。例如4在A区间,7在B区间。
权重越大,落在该区间的概率就越大。这就是加权随机算法。
下面看具体代码实现- public class RandomLoadBalance extends AbstractLoadBalance {
- public static final String NAME = "random";
- private final Random random = new Random();
- @Override
- protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
- int length = invokers.size(); // Number of invokers
- int totalWeight = 0; // The sum of weights
- boolean sameWeight = true; // Every invoker has the same weight?
- // 下面这个循环有两个作用,第一是计算总权重 totalWeight,
- // 第二是检测每个服务提供者的权重是否相同
- for (int i = 0; i < length; i++) {
- int weight = getWeight(invokers.get(i), invocation);
- totalWeight += weight; // Sum
- // 检测当前服务提供者的权重与上一个服务提供者的权重是否相同,
- // 不相同的话,则将 sameWeight 置为 false。
- if (sameWeight && i > 0
- && weight != getWeight(invokers.get(i - 1), invocation)) {
- sameWeight = false;
- }
- }
- if (totalWeight > 0 && !sameWeight) {
- // 随机获取一个 [0, totalWeight) 区间内的数字
- int offset = random.nextInt(totalWeight);
- // Return a invoker based on the random value.
- // 循环让 offset 数减去服务提供者权重值,当 offset 小于0时,返回相应的 Invoker。
- // 举例说明一下,我们有 servers = [A, B, C],weights = [5, 3, 2],offset = 7。
- // 第一次循环,offset - 5 = 2 > 0,即 offset > 5,
- // 表明其不会落在服务器 A 对应的区间上。
- // 第二次循环,offset - 3 = -1 < 0,即 5 < offset < 8,
- // 表明其会落在服务器 B 对应的区间上
- for (int i = 0; i < length; i++) {
- // 让随机值 offset 减去权重值
- offset -= getWeight(invokers.get(i), invocation);
- if (offset < 0) {
- // 返回相应的 Invoker
- return invokers.get(i);
- }
- }
- }
- // 如果所有服务提供者权重值相同,此时直接随机返回一个即可
- return invokers.get(random.nextInt(length));
- }
- }
复制代码 如果权重一致,就随机选择一个。如果权重不同,则根据权重分配。
LeastActiveLoadBalance
最小活跃数负载均衡。这个活跃数表示执行中的请求数量。每个服务提供者对应一个活跃数 active。初始情况下,所有服务提供者活跃数均为0。每收到一个请求,活跃数加1,完成请求后则将活跃数减1。
在流量均匀的情况下,活跃数越低的服务提供者,其性能越好。- protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
- int length = invokers.size(); // Number of invokers
- // 最小的活跃数
- int leastActive = -1; // The least active value of all invokers
- // 具有相同“最小活跃数”的服务者提供者(以下用 Invoker 代称)数量
- int leastCount = 0; // The number of invokers having the same least active value (leastActive)
- // leastIndexs 用于记录具有相同“最小活跃数”的 Invoker 在 invokers 列表中的下标信息
- int[] leastIndexs = new int[length]; // The index of invokers having the same least active value (leastActive)
- int totalWeight = 0; // The sum of with warmup weights
- // 第一个最小活跃数的 Invoker 权重值,用于与其他具有相同最小活跃数的 Invoker 的权重进行对比,
- // 以检测是否“所有具有相同最小活跃数的 Invoker 的权重”均相等
- int firstWeight = 0; // Initial value, used for comparision
- boolean sameWeight = true; // Every invoker has the same weight value?
- // 遍历 invokers 列表
- for (int i = 0; i < length; i++) {
- Invoker<T> invoker = invokers.get(i);
- // 获取 Invoker 对应的活跃数
- int active = RpcStatus.getStatus(invoker.getUrl(), invocation.getMethodName()).getActive(); // Active number
- // 获取权重
- int afterWarmup = getWeight(invoker, invocation); // Weight
- // 发现更小的活跃数,重新开始
- if (leastActive == -1 || active < leastActive) { // Restart, when find a invoker having smaller least active value.
- // 使用当前活跃数 active 更新最小活跃数 leastActive
- leastActive = active; // Record the current least active value
- // 更新 leastCount 为 1
- leastCount = 1; // Reset leastCount, count again based on current leastCount
- // 记录当前下标值到 leastIndexs 中
- leastIndexs[0] = i; // Reset
- totalWeight = afterWarmup; // Reset
- firstWeight = afterWarmup; // Record the weight the first invoker
- sameWeight = true; // Reset, every invoker has the same weight value?
- // 当前 Invoker 的活跃数 active 与最小活跃数 leastActive 相同
- } else if (active == leastActive) { // If current invoker's active value equals with leaseActive, then accumulating.
- // 在 leastIndexs 中记录下当前 Invoker 在 invokers 集合中的下标
- leastIndexs[leastCount++] = i; // Record index number of this invoker
- // 累加权重
- totalWeight += afterWarmup; // Add this invoker's weight to totalWeight.
- // If every invoker has the same weight?
- // 检测当前 Invoker 的权重与 firstWeight 是否相等,
- // 不相等则将 sameWeight 置为 false
- if (sameWeight && i > 0
- && afterWarmup != firstWeight) {
- sameWeight = false;
- }
- }
- }
- // assert(leastCount > 0)
- // 当只有一个 Invoker 具有最小活跃数,此时直接返回该 Invoker 即可
- if (leastCount == 1) {
- // If we got exactly one invoker having the least active value, return this invoker directly.
- return invokers.get(leastIndexs[0]);
- }
- // 有多个 Invoker 具有相同的最小活跃数,但它们之间的权重不同
- if (!sameWeight && totalWeight > 0) {
- // If (not every invoker has the same weight & at least one invoker's weight>0), select randomly based on totalWeight.
- // 随机生成一个 [0, totalWeight) 之间的数字
- int offsetWeight = random.nextInt(totalWeight) + 1;
- // Return a invoker based on the random value.
- // 循环让随机数减去具有最小活跃数的 Invoker 的权重值,
- // 当 offset 小于等于0时,返回相应的 Invoker
- for (int i = 0; i < leastCount; i++) {
- int leastIndex = leastIndexs[i];
- // 获取权重值,并让随机数减去权重值
- offsetWeight -= getWeight(invokers.get(leastIndex), invocation);
- if (offsetWeight <= 0)
- return invokers.get(leastIndex);
- }
- }
- // If all invokers have the same weight value or totalWeight=0, return evenly.
- // 如果权重相同或权重为0时,随机返回一个 Invoker
- return invokers.get(leastIndexs[random.nextInt(leastCount)]);
- }
复制代码 注释写的很详细了,和原理步骤差不多,源码中多个对长时间未更新 invoker 的处理。
ConsistentHashLoadBalance
一致性Hash算法。
其原理简单讲,就是假定有一个圆环,每个服务根据其 hash 值,在圆环上有个位置(如图的cache-1、cache-2等)。当有请求过来的,同样根据请求的 hash 值确定请求的位置,并根据请求的位置去获取最近的下一个服务的位置。如下图:

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

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

以上就是一致性hash算法的原理。下面讲讲Dubbo的源码- @Activate(group = Constants.CONSUMER, value = Constants.ACTIVES_KEY)
- public class ActiveLimitFilter implements Filter
复制代码 doSelect 方法先从缓存获取 selector ,如果缓存没有,则创建并放入缓存。然后调用 selector.select 方法获取 invoker 。所以一致性 hash 的实现,在ConsistentHashSelector中。我们先看其构造方法- <dubbo:service interface="com.alibaba.dubbo.demo.DemoService" ref="demoService" registry="remoteRegistry" actives="5" />
- <dubbo:reference id="demoService" interface="com.alibaba.dubbo.demo.DemoService" loadbalance="leastactive" actives="5" />
复制代码 ConsistentHashSelector的构造方法,主要是计算 invokers 的每一个 invoker 的hash,并将其放入 virtualInvokers 中。从这里可以看到,Dubbo默认的虚拟节点为160个。对比一致性 hash 算法中,virtualInvokers 就是 hash 环,invoker 就是节点。
我们继续看如何从 hash 环中找到最近的节点- <dubbo:reference id="demoService" interface="com.alibaba.dubbo.demo.DemoService" filter="activelimit" />
复制代码 选择的过程也很简单,依赖的是 TreeMap 的 tailMap 方法。
总结
本文介绍了Dubbo内置的4中负载均衡实现。至此,Dubbo的集群容错的四个部分,也就是服务目录 Directory、服务路由 Router、集群 Cluster 和负载均衡 LoadBalance 都已全部讲完。
参考资料
Dubbo开发指南
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |