IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 系统运维 -> 十三:Dubbo负载均衡(三)RoundRobinLoadBalance -> 正文阅读

[系统运维]十三:Dubbo负载均衡(三)RoundRobinLoadBalance

源码

org.apache.dubbo.rpc.cluster.loadbalance.RoundRobinLoadBalance

		//缓存
	    private ConcurrentMap<String, ConcurrentMap<String, WeightedRoundRobin>> methodWeightMap = new ConcurrentHashMap<String, ConcurrentMap<String, WeightedRoundRobin>>();

    @Override
    protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
    	//获取ServiceKey + MethodName 即:com.jiangzheng.course.dubbo.api.service.ServiceDemo.getSelf
        String key = invokers.get(0).getUrl().getServiceKey() + "." + invocation.getMethodName();
        ConcurrentMap<String, WeightedRoundRobin> map = methodWeightMap.computeIfAbsent(key, k -> new ConcurrentHashMap<>());
        //总权重
        int totalWeight = 0;
        //用于判断是否最大权重
        long maxCurrent = Long.MIN_VALUE;
        long now = System.currentTimeMillis();
        Invoker<T> selectedInvoker = null;
        WeightedRoundRobin selectedWRR = null;
        for (Invoker<T> invoker : invokers) {
            //获取不同provider的URL 作为map的key
            String identifyString = invoker.getUrl().toIdentityString();
            //获取权重
            int weight = getWeight(invoker, invocation);
            //在缓存中获取当前循环到的provider URL对应的WeightedRoundRobin
            WeightedRoundRobin weightedRoundRobin = map.computeIfAbsent(identifyString, k -> {
                WeightedRoundRobin wrr = new WeightedRoundRobin();
                wrr.setWeight(weight);
                return wrr;
            });

            //权重如果修改过 则重新设置,因为存在冷起情况,所以权重会有所改变
            if (weight != weightedRoundRobin.getWeight()) {
                //weight changed
                weightedRoundRobin.setWeight(weight);
            }
            //获取当前的 current,第一次为 权重值
            long cur = weightedRoundRobin.increaseCurrent();
            //设置修改时间
            weightedRoundRobin.setLastUpdate(now);
            //判断是否为最大的current,是则将调用对应provider 
            if (cur > maxCurrent) {
                maxCurrent = cur;
                selectedInvoker = invoker;
                selectedWRR = weightedRoundRobin;
            }
            totalWeight += weight;
        }
        if (invokers.size() != map.size()) {
            map.entrySet().removeIf(item -> now - item.getValue().getLastUpdate() > RECYCLE_PERIOD);
        }
      
        if (selectedInvoker != null) {
        	//如果存在最大的 则将 选中的provider对应的weightedRoundRobin 的 current 加上一个 总权重的负数值
            selectedWRR.sel(totalWeight);
            return selectedInvoker;
        }
        // should not happen here
        return invokers.get(0);
    }
    
    protected static class WeightedRoundRobin {
        private int weight;
        private AtomicLong current = new AtomicLong(0);
        private long lastUpdate;

        public int getWeight() {
            return weight;
        }

        public void setWeight(int weight) {
            this.weight = weight;
            current.set(0);
        }

        public long increaseCurrent() {
            return current.addAndGet(weight);
        }

        public void sel(int total) {
            current.addAndGet(-1 * total);
        }

        public long getLastUpdate() {
            return lastUpdate;
        }

        public void setLastUpdate(long lastUpdate) {
            this.lastUpdate = lastUpdate;
        }
    }

算法测试

package com.jiangzheng.course.dubbo.provider.loadbalance;

import com.google.common.collect.Lists;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

public class MyLoadBalance {

    private ConcurrentMap<String, ConcurrentMap<String, MyLoadBalance.WeightedRoundRobin>> methodWeightMap = new ConcurrentHashMap<String, ConcurrentMap<String, MyLoadBalance.WeightedRoundRobin>>();

    private static final int RECYCLE_PERIOD = 60000;

    public static void main(String[] args) {
        MyLoadBalance myLoadBalance = new MyLoadBalance();
        List<Invoker> invokers = Lists.newArrayList();
        for (int i = 1; i < 6; i++) {
            Invoker invoker = new Invoker("IP:" + i, "--------------ServiceDemo--------------", i);
            invokers.add(invoker);
        }
        for (int i = 0; i < 10; i++) {
            Invoker invoker = myLoadBalance.doSelect(invokers, "toSelf");

            System.out.println("选举成功:" + invoker.getIp());
        }
    }

    protected Invoker doSelect(List<Invoker> invokers, String methodName) {
        String key = invokers.get(0).getServiceKey() + "." + methodName;
        ConcurrentMap<String, MyLoadBalance.WeightedRoundRobin> map = methodWeightMap.computeIfAbsent(key, k -> new ConcurrentHashMap<>());
        int totalWeight = 0;
        long maxCurrent = Long.MIN_VALUE;
        long now = System.currentTimeMillis();
        Invoker selectedInvoker = null;
        MyLoadBalance.WeightedRoundRobin selectedWRR = null;
        for (Invoker invoker : invokers) {
            String identifyString = invoker.toIdentityString();
            int weight = invoker.getWeight();
            MyLoadBalance.WeightedRoundRobin weightedRoundRobin = map.computeIfAbsent(identifyString, k -> {
                MyLoadBalance.WeightedRoundRobin wrr = new MyLoadBalance.WeightedRoundRobin();
                wrr.setWeight(weight);
                return wrr;
            });

            if (weight != weightedRoundRobin.getWeight()) {
                //weight changed
                weightedRoundRobin.setWeight(weight);
            }
            long cur = weightedRoundRobin.increaseCurrent();
            weightedRoundRobin.setLastUpdate(now);
            if (cur > maxCurrent) {
                maxCurrent = cur;
                selectedInvoker = invoker;
                selectedWRR = weightedRoundRobin;
            }
            totalWeight += weight;
        }
        if (invokers.size() != map.size()) {
            map.entrySet().removeIf(item -> now - item.getValue().getLastUpdate() > RECYCLE_PERIOD);
        }

        //计算后
        System.out.println("计算后");
        print_table(map.keySet().stream().sorted().collect(Collectors.toList()), map.keySet().stream().sorted().map(e -> map.get(e).current.get() + "").collect(Collectors.toList()));

        if (selectedInvoker != null) {
            selectedWRR.sel(totalWeight);
        }
        System.out.println("选举后");
        print_table(map.keySet().stream().sorted().collect(Collectors.toList()), map.keySet().stream().sorted().map(e -> map.get(e).current.get() + "").collect(Collectors.toList()));

        // should not happen here
        return selectedInvoker != null ? selectedInvoker : invokers.get(0);
    }

    protected static class Invoker {
        private String ip;
        private String serviceKey;
        private int weight;

        public Invoker(String ip, String serviceKey, int weight) {
            this.ip = ip;
            this.serviceKey = serviceKey;
            this.weight = weight;
        }

        public String getIp() {
            return ip;
        }

        public void setIp(String ip) {
            this.ip = ip;
        }

        public String getServiceKey() {
            return serviceKey;
        }

        public void setServiceKey(String serviceKey) {
            this.serviceKey = serviceKey;
        }

        public int getWeight() {
            return weight;
        }

        public void setWeight(int weight) {
            this.weight = weight;
        }

        public String toIdentityString() {
            return ip;
        }

        @Override
        public String toString() {
            return "Invoker{" +
                    "ip='" + ip + '\'' +
                    ", serviceKey='" + serviceKey + '\'' +
                    ", weight=" + weight +
                    '}';
        }
    }

    protected static class WeightedRoundRobin {
        private int weight;
        private AtomicLong current = new AtomicLong(0);
        private long lastUpdate;

        public int getWeight() {
            return weight;
        }

        public void setWeight(int weight) {
            this.weight = weight;
            current.set(0);
        }

        public long increaseCurrent() {
            return current.addAndGet(weight);
        }

        public void sel(int total) {
            current.addAndGet(-1 * total);
        }

        public long getLastUpdate() {
            return lastUpdate;
        }

        public void setLastUpdate(long lastUpdate) {
            this.lastUpdate = lastUpdate;
        }

        @Override
        public String toString() {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
            return "WeightedRoundRobin{" +
                    "weight=" + weight +
                    ", current=" + current +
                    ", lastUpdate=" + simpleDateFormat.format(new Date(lastUpdate)) +
                    '}';
        }
    }

    static void print_table(List<String> title, List<String> table) {
        print_table(title.toArray(new String[title.size()]), title.size(), title.size());
        print_table(table.toArray(new String[table.size()]), table.size(), table.size());
    }

    static void print_table(String[] table, int size, int wide) {
        for (int i = 0; i < wide; ++i) {
            System.out.print("|");
            int len = table[i].length();
//            int left_space =   ①    ;
            int left_space = (size - len) % 2 == 0 ? (size - len) / 2 : (size - len) / 2 + 1;
//            int right_space =    ②    ;
            int right_space = (size - len) / 2;
//            for (int j = 0; j <   ③   ; ++j) {
            //左边空格
            for (int j = 0; j < left_space; ++j) {
                System.out.print(" ");
            }
            System.out.print(table[i]);
            //右边空格
//            for (int j = 0; j <   ④     ; ++j) {
            for (int j = 0; j < right_space; ++j) {
                System.out.print(" ");
            }
        }
        System.out.print("|\n");
        for (int i = 0; i < wide; ++i) {
            System.out.print("+");
            for (int j = 0; j < size; ++j) {
                System.out.print("-");
            }
        }
        System.out.print("+\n");
    }
}

输出结果

计算后
| IP:1| IP:2| IP:3| IP:4| IP:5|
+-----+-----+-----+-----+-----+
|  1  |  2  |  3  |  4  |  5  |
+-----+-----+-----+-----+-----+
选举后
| IP:1| IP:2| IP:3| IP:4| IP:5|
+-----+-----+-----+-----+-----+
|  1  |  2  |  3  |  4  | -10 |
+-----+-----+-----+-----+-----+
选举成功:IP:5
计算后
| IP:1| IP:2| IP:3| IP:4| IP:5|
+-----+-----+-----+-----+-----+
|  2  |  4  |  6  |  8  |  -5 |
+-----+-----+-----+-----+-----+
选举后
| IP:1| IP:2| IP:3| IP:4| IP:5|
+-----+-----+-----+-----+-----+
|  2  |  4  |  6  |  -7 |  -5 |
+-----+-----+-----+-----+-----+
选举成功:IP:4
计算后
| IP:1| IP:2| IP:3| IP:4| IP:5|
+-----+-----+-----+-----+-----+
|  3  |  6  |  9  |  -3 |  0  |
+-----+-----+-----+-----+-----+
选举后
| IP:1| IP:2| IP:3| IP:4| IP:5|
+-----+-----+-----+-----+-----+
|  3  |  6  |  -6 |  -3 |  0  |
+-----+-----+-----+-----+-----+
选举成功:IP:3
计算后
| IP:1| IP:2| IP:3| IP:4| IP:5|
+-----+-----+-----+-----+-----+
|  4  |  8  |  -3 |  1  |  5  |
+-----+-----+-----+-----+-----+
选举后
| IP:1| IP:2| IP:3| IP:4| IP:5|
+-----+-----+-----+-----+-----+
|  4  |  -7 |  -3 |  1  |  5  |
+-----+-----+-----+-----+-----+
选举成功:IP:2
计算后
| IP:1| IP:2| IP:3| IP:4| IP:5|
+-----+-----+-----+-----+-----+
|  5  |  -5 |  0  |  5  |  10 |
+-----+-----+-----+-----+-----+
选举后
| IP:1| IP:2| IP:3| IP:4| IP:5|
+-----+-----+-----+-----+-----+
|  5  |  -5 |  0  |  5  |  -5 |
+-----+-----+-----+-----+-----+
选举成功:IP:5
计算后
| IP:1| IP:2| IP:3| IP:4| IP:5|
+-----+-----+-----+-----+-----+
|  6  |  -3 |  3  |  9  |  0  |
+-----+-----+-----+-----+-----+
选举后
| IP:1| IP:2| IP:3| IP:4| IP:5|
+-----+-----+-----+-----+-----+
|  6  |  -3 |  3  |  -6 |  0  |
+-----+-----+-----+-----+-----+
选举成功:IP:4
计算后
| IP:1| IP:2| IP:3| IP:4| IP:5|
+-----+-----+-----+-----+-----+
|  7  |  -1 |  6  |  -2 |  5  |
+-----+-----+-----+-----+-----+
选举后
| IP:1| IP:2| IP:3| IP:4| IP:5|
+-----+-----+-----+-----+-----+
|  -8 |  -1 |  6  |  -2 |  5  |
+-----+-----+-----+-----+-----+
选举成功:IP:1
计算后
| IP:1| IP:2| IP:3| IP:4| IP:5|
+-----+-----+-----+-----+-----+
|  -7 |  1  |  9  |  2  |  10 |
+-----+-----+-----+-----+-----+
选举后
| IP:1| IP:2| IP:3| IP:4| IP:5|
+-----+-----+-----+-----+-----+
|  -7 |  1  |  9  |  2  |  -5 |
+-----+-----+-----+-----+-----+
选举成功:IP:5
计算后
| IP:1| IP:2| IP:3| IP:4| IP:5|
+-----+-----+-----+-----+-----+
|  -6 |  3  |  12 |  6  |  0  |
+-----+-----+-----+-----+-----+
选举后
| IP:1| IP:2| IP:3| IP:4| IP:5|
+-----+-----+-----+-----+-----+
|  -6 |  3  |  -3 |  6  |  0  |
+-----+-----+-----+-----+-----+
选举成功:IP:3
计算后
| IP:1| IP:2| IP:3| IP:4| IP:5|
+-----+-----+-----+-----+-----+
|  -5 |  5  |  0  |  10 |  5  |
+-----+-----+-----+-----+-----+
选举后
| IP:1| IP:2| IP:3| IP:4| IP:5|
+-----+-----+-----+-----+-----+
|  -5 |  5  |  0  |  -5 |  5  |
+-----+-----+-----+-----+-----+
选举成功:IP:4

Process finished with exit code 0
  系统运维 最新文章
配置小型公司网络WLAN基本业务(AC通过三层
如何在交付运维过程中建立风险底线意识,提
快速传输大文件,怎么通过网络传大文件给对
从游戏服务端角度分析移动同步(状态同步)
MySQL使用MyCat实现分库分表
如何用DWDM射频光纤技术实现200公里外的站点
国内顺畅下载k8s.gcr.io的镜像
自动化测试appium
ctfshow ssrf
Linux操作系统学习之实用指令(Centos7/8均
上一篇文章      下一篇文章      查看所有文章
加:2022-04-01 23:49:45  更:2022-04-01 23:52:14 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/16 0:00:11-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码