Search in sources :

Example 1 with AtomicPositiveInteger

use of com.alibaba.dubbo.common.utils.AtomicPositiveInteger in project dubbo by alibaba.

the class RoundRobinLoadBalance method doSelect.

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) {
            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();
                if (mod == 0 && v.getValue() > 0) {
                    return k;
                }
                if (v.getValue() > 0) {
                    v.decrement();
                    mod--;
                }
            }
        }
    }
    // 取模轮循
    return invokers.get(currentSequence % length);
}
Also used : Invoker(com.alibaba.dubbo.rpc.Invoker) AtomicPositiveInteger(com.alibaba.dubbo.common.utils.AtomicPositiveInteger) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) LinkedHashMap(java.util.LinkedHashMap)

Aggregations

AtomicPositiveInteger (com.alibaba.dubbo.common.utils.AtomicPositiveInteger)1 Invoker (com.alibaba.dubbo.rpc.Invoker)1 LinkedHashMap (java.util.LinkedHashMap)1 Map (java.util.Map)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 ConcurrentMap (java.util.concurrent.ConcurrentMap)1