dubbo源码分析-负载均衡

本文深入探讨Dubbo框架中的四种负载均衡策略:RandomLoadBalance、LeastActiveLoadBalance、ConsistentHashLoadBalance及RoundRobinLoadBalance。每种策略都有其独特的实现原理与应用场景,旨在优化服务调用,提高系统整体性能。

dubbo的负载均衡算法

Dubbo 需要对服务消费者的调用请求进行分配,避免少数服务提供者负载过大。服务提供者负载过大,会导致部分请求超时。因此将负载均衡到每个服务提供者上,是非常必要的。Dubbo 提供了4种负载均衡实现,分别是基于权重随机算法的 RandomLoadBalance、基于最少活跃调用数算法的 LeastActiveLoadBalance、基于 hash 一致性的 ConsistentHashLoadBalance,以及基于加权轮询算法的 RoundRobinLoadBalance

LoadBalance

LoadBalance是一个SPI扩展接口

@SPI("random")
public interface LoadBalance {
    @Adaptive({"loadbalance"})
    <T> Invoker<T> select(List<Invoker<T>> var1, URL var2, Invocation var3) throws RpcException;
}

LoadBalance有4种实现,其中AbstractLoadBalance直接实现LoadBalance,其余实现类继承AbstractLoadBalance

AbstractLoadBalance

public abstract class AbstractLoadBalance implements LoadBalance {
    public AbstractLoadBalance() {
    }

    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);
    }

    public <T> Invoker<T> select(List<Invoker<T>> invokers, URL url, Invocation invocation) {
        if (invokers != null && invokers.size() != 0) {
            return invokers.size() == 1 ? (Invoker)invokers.get(0) : this.doSelect(invokers, url, invocation);
        } else {
            return null;
        }
    }

    protected abstract <T> Invoker<T> doSelect(List<Invoker<T>> var1, URL var2, Invocation var3);

    protected int getWeight(Invoker<?> invoker, Invocation invocation) {
	 // 从 url 中获取权重 weight 配置值
        int weight = invoker.getUrl().getMethodParameter(invocation.getMethodName(), "weight", 100);
        if (weight > 0) {
		 // 获取服务提供者启动时间戳 即开始运行的时间戳
            long timestamp = invoker.getUrl().getParameter("remote.timestamp", 0L);
            if (timestamp > 0L) {
			 // 计算服务提供者运行时长 
                int uptime = (int)(System.currentTimeMillis() - timestamp);
				  // 获取服务预热时间,默认为10分钟
                int warmup = invoker.getUrl().getParameter("warmup", 600000);
				 // 如果服务运行时间小于预热时间,则重新计算服务权重,即降权
                if (uptime > 0 && uptime < warmup) {
                    weight = calculateWarmupWeight(uptime, warmup, weight);
                }
            }
        }

        return weight;
    }
}

该过程主要用于保证当服务运行时长小于服务预热时间时,对服务进行降权,避免让服务在启动之初就处于高负载状态。服务预热是一个优化手段,与此类似的还有 JVM 预热。主要目的是让服务启动后“低功率”运行一段时间,使其效率慢慢提升至最佳状态。

RandomLoadBalance

RandomLoadBalance 是加权随机算法的具体实现,它的算法思想很简单。假设我们有一组服务器 servers = [A, B, C],他们对应的权重为 weights = [5, 3, 2],权重总和为10。现在把这些权重值平铺在一维坐标值上,[0, 5) 区间属于服务器 A,[5, 8) 区间属于服务器 B,[8, 10) 区间属于服务器 C。接下来通过随机数生成器生成一个范围在 [0, 10) 之间的随机数,然后计算这个随机数会落到哪个区间上。比如数字3会落到服务器 A 对应的区间上,此时返回服务器 A 即可。权重越大的机器,在坐标轴上对应的区间范围就越大,因此随机数生成器生成的数字就会有更大的概率落到此区间内。只要随机数生成器产生的随机数分布性很好,在经过多次选择后,每个服务器被选中的次数比例接近其权重比例。比如,经过一万次选择后,服务器 A 被选中的次数大约为5000次,服务器 B 被选中的次数约为3000次,服务器 C 被选中的次数约为2000次。

public class RandomLoadBalance extends AbstractLoadBalance {
    public static final String NAME = "random";
    private final Random random = new Random();

    public RandomLoadBalance() {
    }

    protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
        int length = invokers.size();
        int totalWeight = 0;
        boolean sameWeight = true;

        int offset;
        int i;
		//
        for(offset = 0; offset < length; ++offset) {
		//获取当前服务提供方的权重
            i = this.getWeight((Invoker)invokers.get(offset), invocation);
			//累加获得总权重
            totalWeight += i;
			//计算是否每个服务提供方权重都相同
            if (sameWeight && offset > 0 && i != this.getWeight((Invoker)invokers.get(offset - 1), invocation)) {
                sameWeight = false;
            }
        }
		 // 下面的 if 分支主要用于获取随机数,并计算随机数落在哪个区间上
        if (totalWeight > 0 && !sameWeight) {
		//获得权重区间内随机值
            offset = this.random.nextInt(totalWeight);
			// 循环让 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(i = 0; i < length; ++i) {
                offset -= this.getWeight((Invoker)invokers.get(i), invocation);
                if (offset < 0) {
                    return (Invoker)invokers.get(i);
                }
            }
        }
		 // 如果所有服务提供者权重值相同,此时直接随机返回一个即可
        return (Invoker)invokers.get(this.random.nextInt(length));
    }
}

RandomLoadBalance 的算法思想比较简单,在经过多次请求后,能够将调用请求按照权重值进行“均匀”分配。当然 RandomLoadBalance 也存在一定的缺点,当调用次数比较少时,Random 产生的随机数可能会比较集中,此时多数请求会落到同一台服务器上。这个缺点并不是很严重,多数情况下可以忽略。RandomLoadBalance 是一个简单,高效的负载均衡实现,因此 Dubbo 选择它作为缺省实现。 问题:deSelect方法的参数invokers固定时 可以实现以上的"均匀"分配吧

LeastActiveLoadBalance

LeastActiveLoadBalance 翻译过来是最小活跃数负载均衡。活跃调用数越小,表明该服务提供者效率越高,单位时间内可处理更多的请求。此时应优先将请求分配给该服务提供者。在具体实现中,每个服务提供者对应一个活跃数 active。初始情况下,所有服务提供者活跃数均为0。每收到一个请求,活跃数加1,完成请求后则将活跃数减1。在服务运行一段时间后,性能好的服务提供者处理请求的速度更快,因此活跃数下降的也越快,此时这样的服务提供者能够优先获取到新的服务请求、这就是最小活跃数负载均衡算法的基本思想。除了最小活跃数,LeastActiveLoadBalance 在实现上还引入了权重值。所以准确的来说,LeastActiveLoadBalance 是基于加权最小活跃数算法实现的。举个例子说明一下,在一个服务提供者集群中,有两个性能优异的服务提供者。某一时刻它们的活跃数相同,此时 Dubbo 会根据它们的权重去分配请求,权重越大,获取到新请求的概率就越大。如果两个服务提供者权重相同,此时随机选择一个即可。

public class LeastActiveLoadBalance extends AbstractLoadBalance {
    public static final String NAME = "leastactive";
    private final Random random = new Random();

    public LeastActiveLoadBalance() {
    }

    protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
        int length = invokers.size();
        int leastActive = -1;
        int leastCount = 0;
        int[] leastIndexs = new int[length];
        int totalWeight = 0;
        int firstWeight = 0;
        boolean sameWeight = true;

        int offsetWeight;
        int leastIndex;
        for(offsetWeight = 0; offsetWeight < length; ++offsetWeight) {
            Invoker<T> invoker = (Invoker)invokers.get(offsetWeight);
            leastIndex = RpcStatus.getStatus(invoker.getUrl(), invocation.getMethodName()).getActive();
            int weight = invoker.getUrl().getMethodParameter(invocation.getMethodName(), "weight", 100);
            if (leastActive != -1 && leastIndex >= leastActive) {
                if (leastIndex == leastActive) {
                    leastIndexs[leastCount++] = offsetWeight;
                    totalWeight += weight;
                    if (sameWeight && offsetWeight > 0 && weight != firstWeight) {
                        sameWeight = false;
                    }
                }
            } else {
                leastActive = leastIndex;
                leastCount = 1;
                leastIndexs[0] = offsetWeight;
                totalWeight = weight;
                firstWeight = weight;
                sameWeight = true;
            }
        }

        if (leastCount == 1) {
            return (Invoker)invokers.get(leastIndexs[0]);
        } else {
            if (!sameWeight && totalWeight > 0) {
                offsetWeight = this.random.nextInt(totalWeight);

                for(int i = 0; i < leastCount; ++i) {
                    leastIndex = leastIndexs[i];
                    offsetWeight -= this.getWeight((Invoker)invokers.get(leastIndex), invocation);
                    if (offsetWeight <= 0) {
                        return (Invoker)invokers.get(leastIndex);
                    }
                }
            }

            return (Invoker)invokers.get(leastIndexs[this.random.nextInt(leastCount)]);
        }
    }
}
  1. 遍历 invokers 列表,寻找活跃数最小的 Invoker
  2. 如果有多个 Invoker 具有相同的最小活跃数,此时记录下这些 Invoker 在 invokers 集合中的下标,并累加它们的权重,比较它们的权重值是否相等
  3. 如果只有一个 Invoker 具有最小的活跃数,此时直接返回该 Invoker 即可
  4. 如果有多个 Invoker 具有最小活跃数,且它们的权重不相等,此时处理方式和 RandomLoadBalance 一致
  5. 如果有多个 Invoker 具有最小活跃数,但它们的权重相等,此时随机返回一个即可

ConsistentHashLoadBalance

首先根据 ip 或者其他的信息为缓存节点生成一个 hash,并将这个 hash 投射到 [0, 232 - 1] 的圆环上。当有查询或写入请求时,则为缓存项的 key 生成一个 hash 值。然后查找第一个大于或等于该 hash 值的缓存节点,并到这个节点中查询或写入缓存项。如果当前节点挂了,则在下一次查询或写入缓存时,为缓存项查找另一个大于其 hash 值的缓存节点即可。大致效果如下图所示,每个缓存节点在圆环上占据一个位置。如果缓存项的 key 的 hash 值小于缓存节点 hash 值,则到该缓存节点中存储或读取缓存项。比如下面绿色点对应的缓存项将会被存储到 cache-2 节点中。由于 cache-3 挂了,原本应该存到该节点中的缓存项最终会存储到 cache-4 节点中。

public class ConsistentHashLoadBalance extends AbstractLoadBalance {
    private final ConcurrentMap<String, ConsistentHashLoadBalance.ConsistentHashSelector<?>> selectors = new ConcurrentHashMap();

    public ConsistentHashLoadBalance() {
    }

    protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
        String key = ((Invoker)invokers.get(0)).getUrl().getServiceKey() + "." + invocation.getMethodName();
        int identityHashCode = System.identityHashCode(invokers);
        ConsistentHashLoadBalance.ConsistentHashSelector<T> selector = (ConsistentHashLoadBalance.ConsistentHashSelector)this.selectors.get(key);
        if (selector == null || selector.identityHashCode != identityHashCode) {
            this.selectors.put(key, new ConsistentHashLoadBalance.ConsistentHashSelector(invokers, invocation.getMethodName(), identityHashCode));
            selector = (ConsistentHashLoadBalance.ConsistentHashSelector)this.selectors.get(key);
        }

        return selector.select(invocation);
    }

    private static final class ConsistentHashSelector<T> {
        private final TreeMap<Long, Invoker<T>> virtualInvokers = new TreeMap();
        private final int replicaNumber;
        private final int identityHashCode;
        private final int[] argumentIndex;

        ConsistentHashSelector(List<Invoker<T>> invokers, String methodName, int identityHashCode) {
            this.identityHashCode = identityHashCode;
            URL url = ((Invoker)invokers.get(0)).getUrl();
            this.replicaNumber = url.getMethodParameter(methodName, "hash.nodes", 160);
            String[] index = Constants.COMMA_SPLIT_PATTERN.split(url.getMethodParameter(methodName, "hash.arguments", "0"));
            this.argumentIndex = new int[index.length];

            for(int i = 0; i < index.length; ++i) {
                this.argumentIndex[i] = Integer.parseInt(index[i]);
            }

            Iterator i$ = invokers.iterator();

            while(i$.hasNext()) {
                Invoker<T> invoker = (Invoker)i$.next();
                String address = invoker.getUrl().getAddress();

                for(int i = 0; i < this.replicaNumber / 4; ++i) {
                    byte[] digest = this.md5(address + i);

                    for(int h = 0; h < 4; ++h) {
                        long m = this.hash(digest, h);
                        this.virtualInvokers.put(m, invoker);
                    }
                }
            }

        }

        public Invoker<T> select(Invocation invocation) {
            String key = this.toKey(invocation.getArguments());
            byte[] digest = this.md5(key);
            return this.selectForKey(this.hash(digest, 0));
        }

        private String toKey(Object[] args) {
            StringBuilder buf = new StringBuilder();
            int[] arr$ = this.argumentIndex;
            int len$ = arr$.length;

            for(int i$ = 0; i$ < len$; ++i$) {
                int i = arr$[i$];
                if (i >= 0 && i < args.length) {
                    buf.append(args[i]);
                }
            }

            return buf.toString();
        }

        private Invoker<T> selectForKey(long hash) {
            Long key = hash;
            if (!this.virtualInvokers.containsKey(key)) {
                SortedMap<Long, Invoker<T>> tailMap = this.virtualInvokers.tailMap(key);
                if (tailMap.isEmpty()) {
                    key = (Long)this.virtualInvokers.firstKey();
                } else {
                    key = (Long)tailMap.firstKey();
                }
            }

            Invoker<T> invoker = (Invoker)this.virtualInvokers.get(key);
            return invoker;
        }

        private long hash(byte[] digest, int number) {
            return ((long)(digest[3 + number * 4] & 255) << 24 | (long)(digest[2 + number * 4] & 255) << 16 | (long)(digest[1 + number * 4] & 255) << 8 | (long)(digest[number * 4] & 255)) & 4294967295L;
        }

        private byte[] md5(String value) {
            MessageDigest md5;
            try {
                md5 = MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException var6) {
                throw new IllegalStateException(var6.getMessage(), var6);
            }

            md5.reset();

            byte[] bytes;
            try {
                bytes = value.getBytes("UTF-8");
            } catch (UnsupportedEncodingException var5) {
                throw new IllegalStateException(var5.getMessage(), var5);
            }

            md5.update(bytes);
            return md5.digest();
        }
    }
}

doSelect 方法主要做了一些前置工作,比如检测 invokers 列表是不是变动过,以及创建 ConsistentHashSelector。这些工作做完后,接下来开始调用 ConsistentHashSelector 的 select 方法执行负载均衡逻辑。 ConsistentHashSelector 的构造方法执行了一系列的初始化逻辑,比如从配置中获取虚拟节点数以及参与 hash 计算的参数下标,默认情况下只使用第一个参数进行 hash。需要特别说明的是,ConsistentHashLoadBalance 的负载均衡逻辑只受参数值影响,具有相同参数值的请求将会被分配给同一个服务提供者。ConsistentHashLoadBalance 不 关系权重,因此使用时需要注意一下。

RoundRobinLoadBalance

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

public class RoundRobinLoadBalance extends AbstractLoadBalance { public static final String NAME = "roundrobin"; private final ConcurrentMap<String, AtomicPositiveInteger> sequences = new ConcurrentHashMap();

public RoundRobinLoadBalance() {
}

protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
    String key = ((Invoker)invokers.get(0)).getUrl().getServiceKey() + "." + invocation.getMethodName();
    int length = invokers.size();
    int maxWeight = 0;
    int minWeight = 2147483647;
    LinkedHashMap<Invoker<T>, RoundRobinLoadBalance.IntegerWrapper> invokerToWeightMap = new LinkedHashMap();
    int weightSum = 0;

    int currentSequence;
    for(int i = 0; i < length; ++i) {
        currentSequence = this.getWeight((Invoker)invokers.get(i), invocation);
        maxWeight = Math.max(maxWeight, currentSequence);
        minWeight = Math.min(minWeight, currentSequence);
        if (currentSequence > 0) {
            invokerToWeightMap.put(invokers.get(i), new RoundRobinLoadBalance.IntegerWrapper(currentSequence));
            weightSum += currentSequence;
        }
    }

    AtomicPositiveInteger sequence = (AtomicPositiveInteger)this.sequences.get(key);
    if (sequence == null) {
        this.sequences.putIfAbsent(key, new AtomicPositiveInteger());
        sequence = (AtomicPositiveInteger)this.sequences.get(key);
    }

    currentSequence = sequence.getAndIncrement();
    if (maxWeight > 0 && minWeight < maxWeight) {
        int mod = currentSequence % weightSum;

        for(int i = 0; i < maxWeight; ++i) {
            Iterator i$ = invokerToWeightMap.entrySet().iterator();

            while(i$.hasNext()) {
                Entry<Invoker<T>, RoundRobinLoadBalance.IntegerWrapper> each = (Entry)i$.next();
                Invoker<T> k = (Invoker)each.getKey();
                RoundRobinLoadBalance.IntegerWrapper v = (RoundRobinLoadBalance.IntegerWrapper)each.getValue();
                if (mod == 0 && v.getValue() > 0) {
                    return k;
                }

                if (v.getValue() > 0) {
                    v.decrement();
                    --mod;
                }
            }
        }
    }

    return (Invoker)invokers.get(currentSequence % length);
}

private static final class IntegerWrapper {
    private int value;

    public IntegerWrapper(int value) {
        this.value = value;
    }

    public int getValue() {
        return this.value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public void decrement() {
        --this.value;
    }
}

}

转载于:https://my.oschina.net/odetteisgorgeous/blog/3021424

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值