

public class WeightRoundRobin {
private static Map<String,Weight> weightMap = new HashMap<>();
public static String getServer(){
int totalWeight = 0;
for(Integer weight:WEIGHT_LIST.values()){
totalWeight += weight;
}
if(weightMap.isEmpty()){
WEIGHT_LIST.forEach((ip,weight)->{
weightMap.put(ip,new Weight(ip,weight,0));
});
}
for(Weight weight:weightMap.values()){
weight.setCurrentWeight(weight.getCurrentWeight()+weight.getWeight());
}
Weight maxCurrentWeight = null;
for(Weight weight:weightMap.values()){
if(maxCurrentWeight == null || weight.getCurrentWeight()>maxCurrentWeight.getCurrentWeight()){
maxCurrentWeight = weight;
}
}
maxCurrentWeight.setCurrentWeight(maxCurrentWeight.getCurrentWeight()-totalWeight);
return maxCurrentWeight.getIp();
}
public static void main(String[] args) {
for(int i=0;i<10;i++){
System.out.println(getServer());
}
}
public static final Map<String,Integer> WEIGHT_LIST = new LinkedHashMap<>();
static {
WEIGHT_LIST.put("A",5);
WEIGHT_LIST.put("B",1);
WEIGHT_LIST.put("C",1);
}
}
|