Dubbo源码解析之LoadBalance负载均衡

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/heroqiang/article/details/83310490

阅读须知

  • dubbo版本:2.6.0
  • spring版本:4.3.8
  • 文章中使用/* */注释的方法会做深入分析

正文

dubbo一共支持四种负载均衡策略,RoundRobinLoadBalance(轮询)、RandomLoadBalance(随机)、LeastActiveLoadBalance(最少活跃)、ConsistentHashLoadBalance(一致性哈希)。默认为随机策略,我门在分析consumer调用过程中invoker的选择时,看到了负载均衡策略的应用,下面我们分别来分析一下这四种负载均衡策略的实现细节:
AbstractLoadBalance:

public <T> Invoker<T> select(List<Invoker<T>> invokers, URL url, Invocation invocation) {
    if (invokers == null || invokers.size() == 0)
        return null;
    if (invokers.size() == 1)
        // 如果invoker集合中只有一个,直接返回第一个
        return invokers.get(0);
    /* 子类实现负载均衡选择invoker */
    return doSelect(invokers, url, invocation);
}

首先来看默认的随机策略:
RandomLoadBalance:

protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
    int length = invokers.size();
    int totalWeight = 0;
    // 标识每一个invoker是否有着相同的权重
    boolean sameWeight = true;
    for (int i = 0; i < length; i++) {
        // 遍历获取每一个invoker的权重,权重可以进行配置
        int weight = getWeight(invokers.get(i), invocation);
        totalWeight += weight;
        // 对比当前invoker的权重和上一个invoker的权重
        // 如果发现有权重不相等的,说明不是每一个invoker的权重都一样
        if (sameWeight && i > 0
                && weight != getWeight(invokers.get(i - 1), invocation)) {
            sameWeight = false;
        }
    }
    if (totalWeight > 0 && !sameWeight) {
        // 基于总权重获取随机数
        int offset = random.nextInt(totalWeight);
        for (int i = 0; i < length; i++) {
            // 遍历invoker,用获取的随机数减去当前invoker的权重,如果小于0,则选择当前invoker
            // 如果当前invoker的权重较大,这样差值就更容易小于0,这样选中的几率就越大
            offset -= getWeight(invokers.get(i), invocation);
            if (offset < 0) {
                return invokers.get(i);
            }
        }
    }
    // 如果所有的invoker具有相同的权重值或总权重等于0,则随机返回一个invoker
    return invokers.get(random.nextInt(length));
}

下一个我们来看轮询策略:
RoundRobinLoadBalance:

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;
        }
    }
    AtomicPositiveInteger sequence = sequences.get(key);
    if (sequence == null) {
        sequences.putIfAbsent(key, new AtomicPositiveInteger());
        sequence = sequences.get(key);
    }
    // 当前序列
    int currentSequence = sequence.getAndIncrement();
    if (maxWeight > 0 && minWeight < maxWeight) {
        // 当前序列与总权重取模
        int mod = currentSequence % weightSum;
        for (int i = 0; i < maxWeight; i++) {
            for (Map.Entry<Invoker<T>, IntegerWrapper> each : invokerToWeightMap.entrySet()) {
                final Invoker<T> k = each.getKey();
                final IntegerWrapper v = each.getValue();
                // 当取模值为0或者递减为0后,如果当前invoker的权重值还大于0,则选择当前invoker
                // 这样invoker的权重值越大,则递减之后大于0的概率越大,选中的几率就越大
                if (mod == 0 && v.getValue() > 0) {
                    return k;
                }
                if (v.getValue() > 0) {
                    v.decrement(); // 权重值递减
                    mod--; // 取模值递减
                }
            }
        }
    }
    // 轮询选择
    return invokers.get(currentSequence % length);
}

接下来我们来看最少活跃策略:
LeastActiveLoadBalance:

protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
    int length = invokers.size();
    int leastActive = -1; // 所有invoker的最小活跃值
    int leastCount = 0; // 具有相同最小活跃值的invoker数量(leastActive)
    int[] leastIndexs = new int[length]; // 具有相同最小活跃值的invoker索引(leastActive)
    int totalWeight = 0; // 权重和,总权重
    int firstWeight = 0; // 初始化权重,用来做比较
    boolean sameWeight = true; // 每一个invoker是否有相同的权重值
    for (int i = 0; i < length; i++) {
        Invoker<T> invoker = invokers.get(i);
        // 活跃数量
        int active = RpcStatus.getStatus(invoker.getUrl(), invocation.getMethodName()).getActive();
        // 权重
        int weight = invoker.getUrl().getMethodParameter(invocation.getMethodName(), Constants.WEIGHT_KEY, Constants.DEFAULT_WEIGHT);
        // 当发现具有较小活跃值的invoker时重新开始
        if (leastActive == -1 || active < leastActive) {
            leastActive = active; // 记录当前最小活跃值
            // 重置具有相同最小活跃值的invoker数量,根据当前最小活跃值的invoker数量再次计数
            leastCount = 1;
            leastIndexs[0] = i; // 重置
            totalWeight = weight; // 重置
            firstWeight = weight; // 记录第一个invoker的权重
            sameWeight = true; // 重置
        // 如果当前调invoker的活动值等于leaseActive,则累积
        } else if (active == leastActive) {
            leastIndexs[leastCount++] = i; // 记录这个invoker的index
            totalWeight += weight; // 累加这个invoker的权重到总权重
            // 与初始化权重进行比较,判断是否每一个invoker都具有相同的权重值
            if (sameWeight && i > 0
                    && weight != firstWeight) {
                sameWeight = false;
            }
        }
    }
    if (leastCount == 1) {
        // 如果我们只有一个具有最小活跃值的invoker,则直接返回此invoker
        return invokers.get(leastIndexs[0]);
    }
    if (!sameWeight && totalWeight > 0) {
        // 如果(并非每个invoker具有相同的权重并且至少一个invoker的权重 > 0),则根据totalWeight随机选择
        int offsetWeight = random.nextInt(totalWeight);
        // 根据随机值获取一个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);
        }
    }
    // 如果所有调用者具有相同的权重值或totalWeight = 0,则从具有最小活跃值的集合中随机返回一个
    return invokers.get(leastIndexs[random.nextInt(leastCount)]);
}

最后我们来看一致性哈希策略,一致性哈希,相同参数的请求总是发到同一提供者。当某一台提供者挂时,原本发往该提供者的请求,基于虚拟节点,平摊到其它提供者。默认只对第一个参数Hash,如果要修改,可以配置<dubbo:parameter key="hash.arguments" value="0,1" />。默认使用160个虚拟节点,如果要修改,可以配置<dubbo:parameter key="hash.nodes" value="320" />
ConsistentHashLoadBalance:

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);
    // 这里的identityHashCode主要作用是确定invoker集合是否发生变化
    if (selector == null || selector.identityHashCode != identityHashCode) {
        /* 构建新的一致性哈希选择器并缓存 */
        selectors.put(key, new ConsistentHashSelector<T>(invokers, invocation.getMethodName(), identityHashCode));
        selector = (ConsistentHashSelector<T>) selectors.get(key);
    }
    /* 选择器选择invoker */
    return selector.select(invocation);
}

ConsistentHashLoadBalance.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();
    // 默认160个虚拟节点
    this.replicaNumber = url.getMethodParameter(methodName, "hash.nodes", 160);
    // 默认进行哈希匹配的参数index为0,也就是第一个
    String[] index = Constants.COMMA_SPLIT_PATTERN.split(url.getMethodParameter(methodName, "hash.arguments", "0"));
    // 记录进行哈希匹配的参数的index数组
    argumentIndex = new int[index.length];
    for (int i = 0; i < index.length; i++) {
        argumentIndex[i] = Integer.parseInt(index[i]);
    }
    // 这里的作用个人理解为尽量将每个invoker的虚拟节点均匀的打散在哈希环上
    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);
            }
        }
    }
}

ConsistentHashLoadBalance.ConsistentHashSelector:

public Invoker<T> select(Invocation invocation) {
    // 根据指定进行哈希匹配的参数index取出参数
    String key = toKey(invocation.getArguments());
    byte[] digest = md5(key);
    /* 根据哈希匹配invoker */
    return selectForKey(hash(digest, 0));
}

ConsistentHashLoadBalance.ConsistentHashSelector:

private Invoker<T> selectForKey(long hash) {
    Invoker<T> invoker;
    Long key = hash;
    // 判断虚拟节点映射中是否有匹配的哈希key
    if (!virtualInvokers.containsKey(key)) {
        // 取出映射中key大于或等于给定参数哈希值的部分视图
        SortedMap<Long, Invoker<T>> tailMap = virtualInvokers.tailMap(key);
        if (tailMap.isEmpty()) {
            // 如果取出的部分视图是空的,则直接返回第一个key
            key = virtualInvokers.firstKey();
        } else {
            // 不为空则直接获取部分视图的第一个key
            key = tailMap.firstKey();
        }
    }
    // 根据key取出invoker返回
    invoker = virtualInvokers.get(key);
    return invoker;
}

到这里,整个Dubbo的负载均衡源码分析就完成了。

猜你喜欢

转载自blog.csdn.net/heroqiang/article/details/83310490