平滑加权轮询算法java实现

实现代码

java 复制代码
   /**
     * 功能描述: 平滑加权轮询算法
     *
     * @author zhang pu
     * @date 11:46 2023/9/22
     */
   public static void smoothnessWeightPollLoadBalance() {
        Server serverA = new Server("127.0.0.1", 5, 0);
        Server serverB = new Server("127.0.0.2", 3, 0);
        Server serverC = new Server("127.0.0.3", 2, 0);
        List<Server> serverList = new ArrayList<>();
        serverList.add(serverA);
        serverList.add(serverB);
        serverList.add(serverC);
        int i = 0;
        //模拟10个请求
        while (i < 10)
        {
            for (Server server : serverList)
            {
                server.setCurrentWeight(server.getCurrentWeight() + server.getWeight());
            }
            Collections.sort(serverList);
            //获取最高实时权重的服务器去执行业务
            Server server = serverList.get(0);
            logger.info("执行业务的服务器ip:{}", server.getIp());
            int sum = serverList.stream().mapToInt(Server::getWeight).sum();
            //取出本轮最大的实时权重 - 所以有服务器固定权重之和
            //减权操作
            server.setCurrentWeight(server.getCurrentWeight() - sum);
            logger.info("所有服务器本轮情况:{}", JSON.toJSONString(serverList));
            //进行下一轮
            i++;
        }
    }

实体

java 复制代码
/**
 * @Auther: ZHANG PU
 * @Date: 2023/9/22 13:05
 * @Description:
 */
public class Server implements Comparable {

    /**
     * 服务器ip
     */
    private String ip;
    /**
     * 固定权重
     */
    private int weight;
    /**
     * 动态实时权重
     */
    private int currentWeight;

    public Server() {
    }

    public Server(String ip, int weight, int currentWeight) {
        this.ip = ip;
        this.weight = weight;
        this.currentWeight = currentWeight;
    }

    public String getIp() {
        return ip;
    }

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

    public int getWeight() {
        return weight;
    }

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

    public int getCurrentWeight() {
        return currentWeight;
    }

    public void setCurrentWeight(int currentWeight) {
        this.currentWeight = currentWeight;
    }

    @Override
    public int compareTo(Object o) {
        return ((Server) o).getCurrentWeight() - this.currentWeight;
    }
}

运行结果

相关推荐
2501_940943916 小时前
体系课\ Python Web全栈工程师
开发语言·前端·python
rafael(一只小鱼)6 小时前
AI运维开发平台学习
java·开发语言
b***74886 小时前
C++在系统中的内存对齐
开发语言·c++
散峰而望6 小时前
C++数组(三)(算法竞赛)
开发语言·c++·算法·github
空空kkk6 小时前
SpringMVC——IO笔记
java·io
q***95226 小时前
SpringMVC 请求参数接收
前端·javascript·算法
4***14906 小时前
C++在系统中的编译优化
开发语言·c++
田姐姐tmner6 小时前
Python切片
开发语言·python
oioihoii6 小时前
C++程序执行起点不是main:颠覆你认知的真相
开发语言·c++
初级炼丹师(爱说实话版)6 小时前
多进程与多线程的优缺点及适用场景总结
算法