package com.example.demo.demos.web.nginx;
import java.util.ArrayList;
import java.util.List;
public class WeightedRoundRobin {
private static List<Server> servers = new ArrayList<>(); // 存储服务器的列表
private static int currentIndex = -1; // 当前服务器的索引
private static int currentWeight = 0; // 当前处理的权重
private static int maxWeight = 0; // 所有服务器中的最大权重
private static int gcd; // 所有服务器权重的最大公约数
public static void main(String[] args) {
// 初始化服务器及其权重
servers.add(new Server("服务器1", 4));
servers.add(new Server("服务器2", 2));
servers.add(new Server("服务器3", 2));
// 计算所有服务器权重的最大公约数
gcd = calculateGCD();
// 找到具有最大权重的服务器
maxWeight = getMaxWeight();
// 执行权重轮询算法
for (int i = 0; i < 10; i++) {
Server selectedServer = selectServer();
System.out.println("请求 " + i + " 由 " + selectedServer.getName() + " 处理");
}
}
private static Server selectServer() {
while (true) {
currentIndex = (currentIndex + 1) % servers.size(); // 循环选择下一个服务器
if (currentIndex == 0) {
currentWeight = currentWeight - gcd; // 减少当前权重
if (currentWeight <= 0) {
currentWeight = maxWeight; // 将当前权重重置为最大权重
}
}
if (servers.get(currentIndex).getWeight() >= currentWeight) {
return servers.get(currentIndex); // 返回选择的服务器
}
}
}
private static int calculateGCD() {
int result = servers.get(0).getWeight();
for (int i = 1; i < servers.size(); i++) {
result = gcd(result, servers.get(i).getWeight()); // 计算所有服务器权重的最大公约数
}
return result;
}
private static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b); // 使用欧几里德算法计算最大公约数
}
private static int getMaxWeight() {
int max = 0;
for (Server server : servers) {
if (server.getWeight() > max) {
max = server.getWeight(); // 找到所有服务器中的最大权重
}
}
return max;
}
static class Server {
private String name;
private int weight;
public Server(String name, int weight) {
this.name = name;
this.weight = weight; // 初始化服务器的名称和权重
}
public String getName() {
return name;
}
public int getWeight() {
return weight;
}
}
}
运行结果如下: