Search in sources :

Example 1 with AtomicPositiveInteger

use of com.github.df.restypass.util.AtomicPositiveInteger in project RestyPass by darren-fu.

the class RoundRobinLoadBalancer method doChoose.

@Override
protected ServerInstance doChoose(List<ServerInstance> instanceList, RestyCommand command) {
    String key = command.getServiceName() + "." + command.getPath();
    // 总个数
    int length = instanceList.size();
    // 最大权重
    int maxWeight = 0;
    // 最小权重
    int minWeight = Integer.MAX_VALUE;
    final LinkedHashMap<ServerInstance, IntegerWrapper> invokerToWeightMap = new LinkedHashMap();
    int weightSum = 0;
    for (int i = 0; i < length; i++) {
        int weight = getWeight(instanceList.get(i));
        // 累计最大权重
        maxWeight = Math.max(maxWeight, weight);
        // 累计最小权重
        minWeight = Math.min(minWeight, weight);
        if (weight > 0) {
            invokerToWeightMap.put(instanceList.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<ServerInstance, IntegerWrapper> each : invokerToWeightMap.entrySet()) {
                final ServerInstance instance = each.getKey();
                final IntegerWrapper weight = each.getValue();
                if (mod == 0 && weight.getValue() > 0) {
                    return instance;
                }
                if (weight.getValue() > 0) {
                    weight.decrement();
                    mod--;
                }
            }
        }
    }
    // 取模轮循
    return instanceList.get(currentSequence % length);
}
Also used : AtomicPositiveInteger(com.github.df.restypass.util.AtomicPositiveInteger) ServerInstance(com.github.df.restypass.lb.server.ServerInstance) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) LinkedHashMap(java.util.LinkedHashMap)

Aggregations

ServerInstance (com.github.df.restypass.lb.server.ServerInstance)1 AtomicPositiveInteger (com.github.df.restypass.util.AtomicPositiveInteger)1 LinkedHashMap (java.util.LinkedHashMap)1 Map (java.util.Map)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1