优秀平滑轮询算法

论坛 期权论坛 脚本     
匿名技术用户   2021-1-13 01:07   527   0

public class WeightRoundRobin {
    private static Map<String,Weight> weightMap = new HashMap<>();
    public static String getServer(){
        int totalWeight = 0;
        for(Integer weight:WEIGHT_LIST.values()){
            totalWeight += weight;
        }
        if(weightMap.isEmpty()){
            WEIGHT_LIST.forEach((ip,weight)->{
                weightMap.put(ip,new Weight(ip,weight,0));
            });
        }
        for(Weight weight:weightMap.values()){
            weight.setCurrentWeight(weight.getCurrentWeight()+weight.getWeight());
        }
        Weight maxCurrentWeight = null;
        for(Weight weight:weightMap.values()){
            if(maxCurrentWeight == null || weight.getCurrentWeight()>maxCurrentWeight.getCurrentWeight()){
                maxCurrentWeight = weight;
            }
        }
        maxCurrentWeight.setCurrentWeight(maxCurrentWeight.getCurrentWeight()-totalWeight);
        return maxCurrentWeight.getIp();
    }

    public static void main(String[] args) {
        for(int i=0;i<10;i++){
            System.out.println(getServer());
        }
    }
    public static final Map<String,Integer> WEIGHT_LIST = new LinkedHashMap<>();
    static {
        WEIGHT_LIST.put("A",5);
        WEIGHT_LIST.put("B",1);
        WEIGHT_LIST.put("C",1);
    }

}

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP