Dubbo学习之路(十):集群容错-LoadBalance

12 篇文章 1 订阅

当我们通过路由规则处理以后还是获取到了多个Invoker,但是每次发次调用必然只是调用某一个有效的Invoker,那这个负载均衡的功能就是LoadBalance去实现的,我们依然先来看一下这个几口的实现类和方法。

Invoker<T> invoker = loadbalance.select(invokers, getUrl(), invocation)
public <T> Invoker<T> select(List<Invoker<T>> invokers, URL url, Invocation invocation) {
        if (invokers == null || invokers.isEmpty())
            return null;
        if (invokers.size() == 1)
            return invokers.get(0);
        return doSelect(invokers, url, invocation);
    }

在获取的时候我们其实调用的是loadbalance的doSelect方法

那这里我们可以看到有4中负载方案,我们来一个个讲解

1.RandomLoadBalance(随机):这里的随机跟我们了解的可能有些不同,这里是按照权重来随机的

protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
        //获取当前invoker数量
        int length = invokers.size(); // Number of invokers
        int totalWeight = 0; // The sum of weights
        boolean sameWeight = true; // Every invoker has the same weight?
        //循环所有invoker
        for (int i = 0; i < length; i++) {
            //获取当前invoker的权重
            int weight = getWeight(invokers.get(i), invocation);
            //计算总权重
            totalWeight += weight; // Sum
            //这里判断 到目前为止是不是所有的invoker权重都是一致的
            if (sameWeight && i > 0
                    && weight != getWeight(invokers.get(i - 1), invocation)) {
                sameWeight = false;
            }
        }
        //有权重,但是权重不一致时
        if (totalWeight > 0 && !sameWeight) {
            // 在所有权重总和值中  获取一个随机数
            int offset = random.nextInt(totalWeight);
            // 循环所有的invoker 那随机数-当前invoker的权重,直到获取到的值<0 
            //根据下标获取相应的Invoker
            for (int i = 0; i < length; i++) {
                offset -= getWeight(invokers.get(i), invocation);
                if (offset < 0) {
                    return invokers.get(i);
                }
            }
        }
        // 如果所有的权重都是一致的  按照随机来获取invoker
        return invokers.get(random.nextInt(length));
    }

2.RoundRobinLoadBalance(轮询):这里的随机跟我们了解的可能有些不同,这里是按照权重来轮询的

protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
        String key = invokers.get(0).getUrl().getServiceKey() + "." + invocation.getMethodName();
        //获取所有参与的invoker个数
        int length = invokers.size(); // Number of invokers
        int maxWeight = 0; // The maximum weight
        int minWeight = Integer.MAX_VALUE; // The minimum weight
        //初始化invoker和权重的对应关系MAP
        final LinkedHashMap<Invoker<T>, IntegerWrapper> invokerToWeightMap = new LinkedHashMap<Invoker<T>, IntegerWrapper>();
        int weightSum = 0;
        //循环所有的invoker
        for (int i = 0; i < length; i++) {
            //获取当前invoker的权重
            int weight = getWeight(invokers.get(i), invocation);
            //比较当前权重跟最大权重  获取最大权重值
            maxWeight = Math.max(maxWeight, weight); // Choose the maximum weight
            //比较当前权重跟最小权重  获取最小权重值
            minWeight = Math.min(minWeight, weight); // Choose the minimum weight
            //如果当前invoker权重值>0 设置invoker和权重关系,并且把值加到总权重中
            if (weight > 0) {
                invokerToWeightMap.put(invokers.get(i), new IntegerWrapper(weight));
                weightSum += weight;
            }
        }
        //这里获取当前方法的调用次数
        AtomicPositiveInteger sequence = sequences.get(key);
        if (sequence == null) {
            //为空  初始化次数0 并返回次数
            sequences.putIfAbsent(key, new AtomicPositiveInteger());
            sequence = sequences.get(key);
        }
        //获取已经调用的次数,并且+1
        int currentSequence = sequence.getAndIncrement();
        //如果最大权重>0 并且 最小权重<最大权重  说明权重不一致
        if (maxWeight > 0 && minWeight < maxWeight) {
            //这里根据当前调用次数和权重总和进行取模
            int mod = currentSequence % weightSum;
            //根据最大权重进行循环
            for (int i = 0; i < maxWeight; i++) {
                //循环invoker和权重的对应关系MAP
                for (Map.Entry<Invoker<T>, IntegerWrapper> each : invokerToWeightMap.entrySet()) {
                    final Invoker<T> k = each.getKey();
                    final IntegerWrapper v = each.getValue();
                    //如果取模的结果 ==0 并且当前invoker的权重>0 返回当前invoker
                    if (mod == 0 && v.getValue() > 0) {
                        return k;
                    }
                    //如果取模不为0 并且当前invoker的权重>0
                    //当前invoker权重-1 并且取模值-1
                    if (v.getValue() > 0) {
                        v.decrement();
                        mod--;
                    }
                }
            }
        }
        // 这里直接根据调用次数跟invoker个数进行取模获取invoker
        return invokers.get(currentSequence % length);
    }

3.LeastActiveLoadBalance(最少活跃数):最少活跃调用数,相同活跃数的随机,活跃数指调用前后计数差

protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
        //获取参与计算的invoker数量
        int length = invokers.size(); // Number of invokers
        int leastActive = -1; // The least active value of all invokers
        int leastCount = 0; // The number of invokers having the same least active value (leastActive)
        //初始化一个invoker数量的数组 用于存储最小活跃数的invoker下标
        int[] leastIndexs = new int[length]; // The index of invokers having the same least active value (leastActive)
        int totalWeight = 0; // The sum of weights
        int firstWeight = 0; // Initial value, used for comparision
        boolean sameWeight = true; // Every invoker has the same weight value?
        //循环所有的invoker
        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
            //获取当前invoker的权重
            int weight = invoker.getUrl().getMethodParameter(invocation.getMethodName(), Constants.WEIGHT_KEY, Constants.DEFAULT_WEIGHT); // Weight
            //如果当前最小活跃数为-1 或者 当前invoker的活跃数<最小活跃数
            //设置当前invoker的活跃数为最小活跃数
            //同时把当前invoker下标放到leastIndexs数组中
            if (leastActive == -1 || active < leastActive) { // Restart, when find a invoker having smaller least active value.
                leastActive = active; // Record the current least active value
                leastCount = 1; // Reset leastCount, count again based on current leastCount
                leastIndexs[0] = i; // Reset
                totalWeight = weight; // Reset
                firstWeight = weight; // Record the weight the first invoker
                sameWeight = true; // Reset, every invoker has the same weight value?
            } else if (active == leastActive) { 
                //如果当前invoker的活跃数 == 最小活跃数
                //把当前invoker的下标添加到leastIndexs数组中
                //并且把最小数量+1
                leastIndexs[leastCount++] = i; // Record index number of this invoker
                totalWeight += weight; // Add this invoker's weight to totalWeight.
                // If every invoker has the same weight?
                if (sameWeight && i > 0
                        && weight != firstWeight) {
                    sameWeight = false;
                }
            }
        }
        //当只有一个最小数据时  直接返回当前下标的invoker
        if (leastCount == 1) {
            // If we got exactly one invoker having the least active value, return this invoker directly.
            return invokers.get(leastIndexs[0]);
        }
        if (!sameWeight && totalWeight > 0) {
            //如果权重不一致,总权重>0
            //随机获取总权重(这里是所有最小invoker的权重和)的一个数值
            int offsetWeight = random.nextInt(totalWeight);
            //循环最小invokers
            for (int i = 0; i < leastCount; i++) {
                int leastIndex = leastIndexs[i];
                offsetWeight -= getWeight(invokers.get(leastIndex), invocation);
                //根据权重去计算  知道剩余权重<=0 返回当前下标的invoker
                if (offsetWeight <= 0)
                    return invokers.get(leastIndex);
            }
        }
        //如果所有invoker的权重都一样,随机获取一个最小invoker返回
        return invokers.get(leastIndexs[random.nextInt(leastCount)]);
    }

这里可以看到我们获取活跃数的地方是根据RpcStatus获取的,这个配置规则其实是在dubbo:referenceactives属性,这里设置的是最大活跃数,如果没有配置的话,默认调用一次+1,调用结束-1,那每次调用的增减是在哪里执行的呢?

其实是在com.alibaba.dubbo.rpc.filter.ActiveLimitFilter中

public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        URL url = invoker.getUrl();
        String methodName = invocation.getMethodName();
        int max = invoker.getUrl().getMethodParameter(methodName, Constants.ACTIVES_KEY, 0);
        RpcStatus count = RpcStatus.getStatus(invoker.getUrl(), invocation.getMethodName());
        if (max > 0) {
            long timeout = invoker.getUrl().getMethodParameter(invocation.getMethodName(), Constants.TIMEOUT_KEY, 0);
            long start = System.currentTimeMillis();
            long remain = timeout;
            int active = count.getActive();
            if (active >= max) {
                synchronized (count) {
                    while ((active = count.getActive()) >= max) {
                        try {
                            count.wait(remain);
                        } catch (InterruptedException e) {
                        }
                        long elapsed = System.currentTimeMillis() - start;
                        remain = timeout - elapsed;
                        if (remain <= 0) {
                            throw new RpcException("Waiting concurrent invoke timeout in client-side for service:  "
                                    + invoker.getInterface().getName() + ", method: "
                                    + invocation.getMethodName() + ", elapsed: " + elapsed
                                    + ", timeout: " + timeout + ". concurrent invokes: " + active
                                    + ". max concurrent invoke limit: " + max);
                        }
                    }
                }
            }
        }
        try {
            long begin = System.currentTimeMillis();
            RpcStatus.beginCount(url, methodName);
            try {
                Result result = invoker.invoke(invocation);
                RpcStatus.endCount(url, methodName, System.currentTimeMillis() - begin, true);
                return result;
            } catch (RuntimeException t) {
                RpcStatus.endCount(url, methodName, System.currentTimeMillis() - begin, false);
                throw t;
            }
        } finally {
            if (max > 0) {
                synchronized (count) {
                    count.notify();
                }
            }
        }
    }

真正加减是在RpcStatus.beginCount(url, methodName);和RpcStatus.endCount方法

public static void beginCount(URL url, String methodName) {
        beginCount(getStatus(url));
        beginCount(getStatus(url, methodName));
    }

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

    /**
     * @param url
     * @param elapsed
     * @param succeeded
     */
    public static void endCount(URL url, String methodName, long elapsed, boolean succeeded) {
        endCount(getStatus(url), elapsed, succeeded);
        endCount(getStatus(url, methodName), elapsed, succeeded);
    }

    private static void endCount(RpcStatus status, long elapsed, boolean succeeded) {
        status.active.decrementAndGet();
        status.total.incrementAndGet();
        status.totalElapsed.addAndGet(elapsed);
        if (status.maxElapsed.get() < elapsed) {
            status.maxElapsed.set(elapsed);
        }
        if (succeeded) {
            if (status.succeededMaxElapsed.get() < elapsed) {
                status.succeededMaxElapsed.set(elapsed);
            }
        } else {
            status.failed.incrementAndGet();
            status.failedElapsed.addAndGet(elapsed);
            if (status.failedMaxElapsed.get() < elapsed) {
                status.failedMaxElapsed.set(elapsed);
            }
        }
    }

4.ConsistentHashLoadBalance(一致性hash),将整个哈希值空间组织成一个虚拟的圆环,圆环由2^32-1个节点组成,我们通过将被选取的东西的值跟2^32-1进行取模运算,获取被选中的节点在圆上的位置,当有一个需要计算的数据到来时,依然是跟2^32-1进行取模运算,然后得到一个圆上的值,顺时针转动,第一个服务器节点就是我们需要得到的值。

1.一致性 Hash,相同参数的请求总是发到同一提供者

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

3.缺省只对第一个参数 Hash,160 份虚拟节点,可配置(由于被选择的节点太少,这个算法可能导致分配不均匀,这个时候虚拟节点就诞生了,把真实节点通过某个算法生成N个虚拟节点,然后拿真实节点和虚拟节点进行圆环上的匹配)

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

1.根据传入的所有invokers,生成一个hashcode

2.根据当前类+方法名称,获取对应的ConsistentHashSelector

3.如果没有获取到,实例化一个ConsistentHashSelector

ConsistentHashSelector(List<Invoker<T>> invokers, String methodName, int identityHashCode) {
            this.virtualInvokers = new TreeMap<Long, Invoker<T>>();
            this.identityHashCode = identityHashCode;
            URL url = 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"));
            argumentIndex = new int[index.length];
            for (int i = 0; i < index.length; i++) {
                argumentIndex[i] = Integer.parseInt(index[i]);
            }
            for (Invoker<T> invoker : invokers) {
                ③ String address = invoker.getUrl().getAddress();
                for (int i = 0; i < replicaNumber / 4; i++) {
                    byte[] digest = md5(address + i);
                    for (int h = 0; h < 4; h++) {
                        long m = hash(digest, h);
                        virtualInvokers.put(m, invoker);
                    }
                }
            }
        }

3.1获取到配置的虚拟节点个数,如果没有,默认160

3.2获取所有参与HASH的字段下标信息,进行初始化

3.3循环每个Invoker,拿到地址信息,进行md5计算,然后进行hash,生成虚拟节点和Invoker的对应关系

4.根据请求的信息,获取对应的Invoker

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

        private String toKey(Object[] args) {
            StringBuilder buf = new StringBuilder();
            for (int i : argumentIndex) {
                if (i >= 0 && i < args.length) {
                    buf.append(args[i]);
                }
            }
            return buf.toString();
        }

        private Invoker<T> selectForKey(long hash) {
            Map.Entry<Long, Invoker<T>> entry = virtualInvokers.tailMap(hash, true).firstEntry();
        	if (entry == null) {
        		entry = virtualInvokers.firstEntry();
        	}
        	return entry.getValue();
        }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值