权重轮询调度算法(WeightedRound-RobinScheduling)-Java实现3
权重轮询调度算法(WeightedRound-RobinScheduling)-Java实现3
之前两篇相关博文:
权重轮询调度算法(WeightedRound-RobinScheduling)-Java实现
http://www.cnblogs.com/huligong1234/p/3819979.html
权重轮询调度算法(WeightedRound-RobinScheduling)-Java实现2
http://www.cnblogs.com/huligong1234/p/3862665.html
之前两篇讲到的方案都稍复杂些,在实际项目中,对权重轮询精确要求不高的情况下,还可以有更简便的方式,就是利用Java自带的Random来实现。
(当然也可以利用Collections.shuffle()来达到目的)
示例代码如下:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/**
* 权重轮询调度算法(WeightedRound-RobinScheduling)-Java实现
* @author huligong
* */
public class WeightedRoundRobinScheduling {
public static void main(String[] args) {
Map<String,Integer> serverWeight = new HashMap<String,Integer>();
serverWeight.put("192.168.1.100", 6);//ip,权重
serverWeight.put("192.168.1.101", 3);
serverWeight.put("192.168.1.102", 2);
serverWeight.put("192.168.1.104", 1);
String ip = getServer(serverWeight);
}
public static String getServer(Map<String,Integer> serverWeight){
Random random = new Random();
ArrayList<String> serverList = new ArrayList<String>();
for(Map.Entry<String, Integer> m : serverWeight.entrySet()){
for(int i=0,len=m.getValue();i<len;i++){
serverList.add(m.getKey());
}
}
String[] servers = serverList.toArray(new String[serverList.size()]);
int weight_idx = random.nextInt(servers.length);
String ip = servers[weight_idx];
return ip;
}
}