码迷,mamicode.com
首页 > 其他好文 > 详细

今日份奇思妙想——根据权重负载均衡

时间:2021-06-16 18:35:22      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:integer   foreach   array   for   span   vat   his   ring   exti   

public class WeightProcessor {

    private final Map<Integer, List<String>> map = new HashMap<>(); //保存权重值和地址
    private final Integer[] weight; //保存权重值,用于负载均衡
    private final Random random = new Random();

    WeightProcessor(Map<String, Integer> map) {
        List<Integer> list = new ArrayList<>();

        map.forEach((k, v) -> {
            for (int i = 0; i < v; i++) {
                list.add(v);
            }
            if (this.map.get(v) == null) {
                this.map.put(v, new ArrayList<String>(){{add(k);}});
            } else {
                this.map.get(v).add(k);
            }
        });

        this.weight = list.toArray(new Integer[list.size()]);
    }

    public String getAddress() {
        int num = random.nextInt(weight.length);
        List<String> list = map.get(weight[num]);
        num = random.nextInt(list.size());
        return list.get(num);
    }

    public static void main(String[] args) {

        Map<String, Integer> map = new HashMap<String, Integer>(){{
            put("127.0.0.1:8080", 2);
            put("127.0.0.1:8888", 8);
            put("127.0.0.1:6666", 2);
        }};

        WeightProcessor processor = new WeightProcessor(map);
        System.out.println(processor.getAddress());
        System.out.println(processor.getAddress());
        System.out.println(processor.getAddress());
        System.out.println(processor.getAddress());
        System.out.println(processor.getAddress());
        System.out.println(processor.getAddress());
        System.out.println(processor.getAddress());
        System.out.println(processor.getAddress());
        System.out.println(processor.getAddress());
        System.out.println(processor.getAddress());
    }
}

主方法中的是测试方法,思路是将配置文件中的数据以Map的形式读取出来,然后创建负载处理器,根据负载会选择一个节点的地址进行访问。

今日份奇思妙想——根据权重负载均衡

标签:integer   foreach   array   for   span   vat   his   ring   exti   

原文地址:https://www.cnblogs.com/wxdmw/p/14889806.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!