基于权重的随机负载均衡路由算法

样例

private Map serverMap = new HashMap(){{
        put("192.168.1.100",1);
        put("192.168.1.101",1);
        put("192.168.1.102",4);
        put("192.168.1.103",1);
        put("192.168.1.104",1);
        put("192.168.1.105",3);
        put("192.168.1.106",1);
        put("192.168.1.107",2);
        put("192.168.1.108",1);
        put("192.168.1.109",1);
        put("192.168.1.110",1);
    }};

    private List servers = new ArrayList<>(serverMap.keySet());

实现一

public void weightRandom(){
        Set keySet = serverMap.keySet();
        List servers = new ArrayList();
        for(Iterator it = keySet.iterator();it.hasNext();){
            String server = it.next();
            int weight = serverMap.get(server);
            for(int i=0;i

实现二

public String randomWeight(){
        int length = serverMap.size(); // 总个数
        int totalWeight = 0; // 总权重
        boolean sameWeight = true; // 权重是否都一样
        for (int i = 0; i < length; i++) {
            int weight = serverMap.get(servers.get(i));
            totalWeight += weight; // 累计总权重
            if (sameWeight && i > 0
                    && weight != serverMap.get(servers.get(i-1))) {
                sameWeight = false; // 计算所有权重是否一样
            }
        }
        if (totalWeight > 0 && ! sameWeight) {
            // 如果权重不相同且权重大于0则按总权重数随机
            int offset = ThreadLocalRandom.current().nextInt(totalWeight);
            // 并确定随机值落在哪个片断上
            for (int i = 0; i < length; i++) {
                offset -= serverMap.get(servers.get(i));
                if (offset < 0) {
                    return servers.get(i);
                }
            }
        }
        // 如果权重相同或权重为0则均等随机
        return servers.get(ThreadLocalRandom.current().nextInt(length));
    }

doc

  • dubbo-RandomLoadBalance

想获取最新内容,请关注微信公众号

基于权重的随机负载均衡路由算法_第1张图片
qrcode_for_gh_121b87c80448_258.jpg

你可能感兴趣的:(基于权重的随机负载均衡路由算法)