实现代码
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;
}
}