(二)负载均衡

xiaoxiao2021-02-28  121

负载均衡  

1.加权随机

配置:loadbalance="random"(默认是random),权重:weight="100"(默认权重是100)

获取接口的权重,如果接口的启动时间大于10分钟(600000毫秒),则重新计算权重weight

public class RandomLoadBalance extends AbstractLoadBalance {     protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {         int length = invokers.size(); //提供者的总个数         int totalWeight = 0; //提供者的总权重         boolean sameWeight = true; //用来标记 提供者列表中的权重是否都一样         //1处,计算所有提供者的权重总和         for (int i = 0; i < length; i++) {             int weight = getWeight(invokers.get(i), invocation);             totalWeight += weight; // 累计总权重             if (sameWeight && i > 0                     && weight != getWeight(invokers.get(i - 1), invocation)) {                 //2处,第i个提供者和第个提供者的权重比较,是否一样,不一样则标记sameWight=false。                 sameWeight = false; // 计算所有权重是否一样             }         }         //3处,根据权重范围段随机获取一个提供者         if (totalWeight > 0 && ! sameWeight) {             // 如果权重不相同且权重大于0则按总权重数随机             int offset = random.nextInt(totalWeight);             // 并确定随机值落在哪个片断上             for (int i = 0; i < length; i++) {                 offset -= getWeight(invokers.get(i), invocation);                 if (offset < 0) {                     return invokers.get(i);                 }             }         }         //4处,如果权重相同或权重为0则均等随机         return invokers.get(random.nextInt(length));     } }

将所有提供者列表的权重累加起来totalWeigth,并随机生成一个(0 - totalWeight)随机数,依次减去列表的权重,小于0则为取到的提供者 具体看上面源码的“1处”,计算所有提供者的权重总和,其中“2处”,第i个提供者和第个提供者的权重比较,是否一样,不一样则标记sameWight=false。

“3处”,根据权重范围段随机获取一个提供者;“4处”,如果权重相同或权重为0则均等随机。

2.随机循环

配置:loadbalance="roundrobin"

public class RoundRobinLoadBalance extends AbstractLoadBalance { public static final String NAME = "roundrobin"; private final ConcurrentMap<String, AtomicPositiveInteger> sequences = new ConcurrentHashMap<String, AtomicPositiveInteger>(); private static final class IntegerWrapper { public IntegerWrapper(int value) { this.value = value; } private int value; public int getValue() { return value; } public void setValue(int value) { this.value = value; } public void decrement() { this.value--; } } protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) { String key = invokers.get(0).getUrl().getServiceKey() + "." + invocation.getMethodName(); int length = invokers.size(); // 总个数 int maxWeight = 0; // 最大权重 int minWeight = Integer.MAX_VALUE; // 最小权重 final LinkedHashMap<Invoker<T>, IntegerWrapper> invokerToWeightMap = new LinkedHashMap<Invoker<T>, IntegerWrapper>(); int weightSum = 0; for (int i = 0; i < length; i++) { int weight = getWeight(invokers.get(i), invocation); maxWeight = Math.max(maxWeight, weight); // 累计最大权重 minWeight = Math.min(minWeight, weight); // 累计最小权重 if (weight > 0) { //Invoker对应权重关系 invokerToWeightMap.put(invokers.get(i), new IntegerWrapper(weight)); //累加总的权重 weightSum += weight; } } //sequence,每个接口方法的序列号 AtomicPositiveInteger sequence = sequences.get(key); if (sequence == null) { sequences.putIfAbsent(key, new AtomicPositiveInteger()); sequence = sequences.get(key); } //21处,接口方法的调用序列号,currentSequence每个接口调用次数,getAndIncrement(),每调用一次,则序列号会递增1,即表示方法调用次数多了一次。 //sequence是dubbo自定义的AtomicPositiveInteger类型对象,即保证sequence的值不为负数,当值递增到int类型的最大值((2 ^ 31) -1)时,值会重新归0,保证值不为负。 int currentSequence = sequence.getAndIncrement(); if (maxWeight > 0 && minWeight < maxWeight) { // 权重不一样 //22处,计算mod的值 int mod = currentSequence % weightSum; for (int i = 0; i < maxWeight; i++) { //23处,循环减去权重 for (Map.Entry<Invoker<T>, IntegerWrapper> each : invokerToWeightMap.entrySet()) { final Invoker<T> k = each.getKey(); //每一个Invoker提供者 final IntegerWrapper v = each.getValue(); //Invoker提供者对应的权重 if (mod == 0 && v.getValue() > 0) { // return k; } if (v.getValue() > 0) { v.decrement(); //提供者的权重和mod的值同时增减。 mod--; } } } } // 取模轮循 return invokers.get(currentSequence % length); } }

 

 

看“21处”, 接口方法的调用序列号,currentSequence每个接口调用次数,getAndIncrement(),每调用一次,则序列号会递增1,即表示方法调用次数多了一次。 sequence是dubbo自定义的AtomicPositiveInteger类型对象,即保证sequence的值不为负数,当值递增到int类型的最大值((2 ^ 31) -1)时,值会重新归0,保证值不为负。 看“22处”计算mod的值, weightSum是固定的(除非提供者的权重发生变化),而每调用一次接口,currentSequence序列就加1, 所以currentSequence会先递增到最大,然后归零再最大,如此循环下去。 mod的值也随着currentSequence的值变化,由0 - (weightSum - 1) - 0 - (weightSum - 1) - ... 看“23处”的循环, for循环完成所有Invoker提供者,mod每遇到一个Invoker,mod值会减少1,Invoker的权重也会减少1(如果它的权重还大于0),循环完一圈,又从头开始。 直到mod减完变为0,而Invoker的权重值还大于0,则该Invoker(比如第i个提供者)就被选中,由此可见权重越大的提供者,则可以坚持留到最后, 而到了下一次调用接口时,mod的值会随着currentSequence加1而加1,那么mod会在第i+1个Invoker时才变为0,而这次就是第i+1个Invoker提供者被选中。 比如, Invoker提供者:权重 1:3 2:1 3:4 4:5 则weightSum=13 第1次调用时,currentSequence = 0,即mod = 0,当mod为0时,循环轮到第1个Invoker,而且Invoker(1:3)权重是3,则第1个Invoker被选中。 第2次调用时,currentSequence = 1,即mod = 1,当mod为0时,循环轮到第2个Invoker,而且Invoker(2:1)权重是1,则第2个Invoker被选中。 第3次调用时,currentSequence = 2,即mod = 2,当mod为0时,循环轮到第3个Invoker,而且Invoker(3:4)权重是4,则第3个Invoker被选中。 第4次调用时,currentSequence = 3,即mod = 3,当mod为0时,循环轮到第4个Invoker,而且Invoker(4:4)权重是5,则第4个Invoker被选中。 第5次调用时,currentSequence = 4,即mod = 4,当mod为0时,循环轮到第1个Invoker,而且Invoker(1:2)权重是2,因为它第一圈权重时已经减少1,则第1个Invoker被选中。 第6次调用时,currentSequence = 5,即mod = 5,当mod为0时,循环轮到第3个Invoker,因为第2个Invoker在第一圈后权重变为0,而且Invoker(3:3)权重是3,则第3个Invoker被选中。 . . .

 

 

 

如此循环下去,每个Invoker提供者都会被选中,而权重大的被选中的次数也就多。

 

3.最少活跃

配置:loadbalance="leastactive"

public class LeastActiveLoadBalance extends AbstractLoadBalance { public static final String NAME = "leastactive"; private final Random random = new Random(); 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; // 是否所有权重相同 //31处 for (int i = 0; i < length; i++) { Invoker<T> invoker = invokers.get(i); //311处 int active = RpcStatus.getStatus(invoker.getUrl(), invocation.getMethodName()).getActive(); // 活跃数 int weight = invoker.getUrl().getMethodParameter(invocation.getMethodName(), Constants.WEIGHT_KEY, Constants.DEFAULT_WEIGHT); // 权重 if (leastActive == -1 || active < leastActive) { // 发现更小的活跃数,重新开始 leastActive = active; // 记录最小活跃数 leastCount = 1; // 重新统计相同最小活跃数的个数 leastIndexs[0] = i; // 重新记录最小活跃数下标 totalWeight = weight; // 重新累计总权重 firstWeight = weight; // 记录第一个权重 sameWeight = true; // 还原权重相同标识 } else if (active == leastActive) { // 累计相同最小的活跃数 leastIndexs[leastCount ++] = i; // 累计相同最小活跃数下标 totalWeight += weight; // 累计总权重 // 判断所有权重是否一样 if (sameWeight && i > 0 && weight != firstWeight) { sameWeight = false; } } } //32处 // assert(leastCount > 0) if (leastCount == 1) { // 如果只有一个最小则直接返回 return invokers.get(leastIndexs[0]); } //33处 if (! sameWeight && totalWeight > 0) { // 如果权重不相同且权重大于0则按总权重数随机 int offsetWeight = random.nextInt(totalWeight); // 并确定随机值落在哪个片断上 for (int i = 0; i < leastCount; i++) { int leastIndex = leastIndexs[i]; offsetWeight -= getWeight(invokers.get(leastIndex), invocation); if (offsetWeight <= 0) return invokers.get(leastIndex); } } //34处 // 如果权重相同或权重为0则均等随机 return invokers.get(leastIndexs[random.nextInt(leastCount)]); } }

说明:

 

提供者的活跃数:提供者的并发数,就是有多少个消费者在同时调用提供者。

在每调用提供者之前会调用com.alibaba.dubbo.rpc.RpcStatus.beginCount(RpcStatus)

private static void beginCount(RpcStatus status) { status.active.incrementAndGet(); }

调用结束后,包括正常结束,或是异常返回,都会调用com.alibaba.dubbo.rpc.RpcStatus.endCount(RpcStatus status, long elapsed, boolean succeeded)

private static void endCount(RpcStatus status, long elapsed, boolean succeeded) { status.active.decrementAndGet(); //省略其他代码。。。 }

 

在源码的“31处”,循环每一个调用者,其中源码的“311处”就是获取提供者的活跃数,找出最小活跃数的调用者。 在源码的“32处”,如果只有一个最小活跃的提供者,则返回它。 在源码的“33处”,如果最小活跃数是相同的多个提供者,则按照这些提供者的权重随机返回一个。 在源码的“34处”,如果最小活跃的提供者权重都相等,则随便返回一个提供者。

自己写了个RPC:

https://github.com/nytta

可以给个star,^0^.

转载请注明原文地址: https://www.6miu.com/read-58676.html

最新回复(0)