nignx的权重算法的具体逻辑流程如下 ,以(7,2,1)权重比例为例
A B C
0 0 0 初试状态
7 2 1 选中A
-3 2 1
4 4 2 选中A
-6 4 2
1 6 3 选中B
1 -4 3
8 -2 4 选中A
-2 -2 4
5 0 5 选中A
-5 0 5
2 2 6 选中C
2 2 -4
9 4 -3 选中A
-1 4 -3
6 6 -2 选中A
-4 6 -2
3 8 -1 选中B
3 -2 -1
10 0 0 选中A
0 0 0
依次循环
第一次是初始值0,0,0 其次就是根据具体的权重分配如(7,2,1) 选择最高权重减去权重之和,然后获得第二的值(-3,2,1)选择第二次的权重最高减去权重之和,等等等等,循环
具体代码如下
权重设置类
public class PowerWeight {
protected String resource;
protected int weight;
public PowerWeight(String resource, int weight) {
this.resource = resource;
this.weight = weight;
}
}
权重逻辑代码
import java.util.Arrays;
import java.util.stream.Collectors;
public class WeightAlgorithm {
class WA{
PowerWeight pw;
int current =0;
WA(PowerWeight pw){
this.pw = pw;
}
}
final WA[] cacheWeights ;
public WeightAlgorithm(PowerWeight[] powerWeights) {
this.cacheWeights = Arrays.stream(powerWeights)
.map(WA::new).collect(Collectors.toList()).toArray(new WA[0]);
}
public String next(){
int total =0 ;
WA shed = cacheWeights[0];
for (WA item : cacheWeights) {
int weight = item.pw.weight;
total += weight;
item.current += weight;
if (item.current > shed.current){
shed = item;
}
}
shed.current -= total;
return shed.pw.resource;
}
}
测试类
public class PowerWeightTest {
public static void main(String[] args) {
PowerWeight[] powerWeights = new PowerWeight[]{
new PowerWeight("A",7),
new PowerWeight("B",2),
new PowerWeight("C",1)
};
int count = 10;
WeightAlgorithm wa = new WeightAlgorithm(powerWeights);
for (int i = 0; i < count; i++) {
System.out.print(wa.next() +",");
}
}
}
测试结果