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 MapweightMap = 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(); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)