实现代码
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;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++;}}
实体
public class Server implements Comparable {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;}@Overridepublic int compareTo(Object o) {return ((Server) o).getCurrentWeight() - this.currentWeight;}
}
运行结果