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

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的形式读取出来,然后创建负载处理器,根据负载会选择一个节点的地址进行访问。

posted @ 2021-06-16 16:09  无心大魔王  阅读(56)  评论(0编辑  收藏  举报