负载均衡之权重算法

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() +",");
        }

    }
}

测试结果

5ae34179ed4b4d0480a71ba1e10129ab.png

 

 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值