Nignx平滑加权轮询算法

Nignx平滑加权轮询算法,第1张

Nignx平滑加权轮询算法

Nignx平滑加权轮询算法

public class Weight {
    private Integer index;
    private Integer weight;
    private Integer currentWeight;

    public Weight(Integer index, Integer weight, Integer currentWeight) {
        this.index = index;
        this.weight = weight;
        this.currentWeight = currentWeight;
    }

    public Integer getIndex() {
        return index;
    }

    public void setIndex(Integer index) {
        this.index = index;
    }

    public Integer getWeight() {
        return weight;
    }

    public void setWeight(Integer weight) {
        this.weight = weight;
    }

    public Integer getCurrentWeight() {
        return currentWeight;
    }

    public void setCurrentWeight(Integer currentWeight) {
        this.currentWeight = currentWeight;
    }
}
```java

public class Test {
    public static void main(String[] args) {
        int countA = 0;
        int countB = 0;
        for (int i = 0; i < 9985; i++) {
            if(weightRoundRobin()==0) {
                countA++;
            }else{
                countB++;
            }

        }
        System.out.println(countA);
        System.out.println(countB);
    }
    
    private static Map weightMap = new linkedHashMap<>();

    static {
        if (weightMap.isEmpty()) {
            weightMap.put(0, new Weight(0, 15, 0));
            weightMap.put(1, new Weight(1, 85, 0));
//            weightMap.put(2, new Weight(2, 1, 0));
        }
    }

    public static int weightRoundRobin() {
        int totalWeight = 0;
        for (Weight weight : weightMap.values()) {
            totalWeight += weight.getWeight();
        }
        //1 currentWeight+=weight
        for (Weight weight : weightMap.values()) {
            weight.setCurrentWeight(weight.getCurrentWeight() + weight.getWeight());
        }
        //2 max(currentWeight)
        Weight maxCurrentWeight = null;
        for (Weight weight : weightMap.values()) {
            if (maxCurrentWeight == null || weight.getCurrentWeight() > maxCurrentWeight.getCurrentWeight()) {
                maxCurrentWeight = weight;
            }
        }
        //3. max(currentWeight) -= sum(weight)
        maxCurrentWeight.setCurrentWeight(maxCurrentWeight.getCurrentWeight() - totalWeight);
        return maxCurrentWeight.getIndex();
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5708635.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存