Nginx常用来做负载均衡,那么Nginx常见的算法都有哪些呢?
public class IpMap {
//待路由的Ip列表,Key代表Ip,Value代表该Ip的权重
public static HashMap<String,Integer>serverWeightMap=new HashMap<String,Integer>();
static{
serverWeightMap.put("192.168.1.100",1);
serverWeightMap.put("192.168.1.101",1);
//权重为4
serverWeightMap.put("192.168.1.102",4);
serverWeightMap.put("192.168.1.103",1);
serverWeightMap.put("192.168.1.104",1);
//权重为3
serverWeightMap.put("192.168.1.105",3);
serverWeightMap.put("192.168.1.106",1);
//权重为2
serverWeightMap.put("192.168.1.107",2);
serverWeightMap.put("192.168.1.108",1);
serverWeightMap.put("192.168.1.109",1);
serverWeightMap.put("192.168.1.110",1);
}
}
1.Nginx默认的算法是轮询算法:
即每两次请求,将下一次的请求分发给下一个服务器
/**
轮询算法
**/
public class RoundRobin {
private static Integer pos=0;
public static String getServer(){
//重建一个Map,避免服务器的上下线导致的并发问题
Map<String,Integer> serverMap=new HashMap<String,Integer>();
serverMap.putAll(IpMap.serverWeightMap);
//取得Ip地址List
Set<String>keySet=serverMap.keySet();
ArrayList<String>keylist=new ArrayList<String>();
keylist.addAll(keySet);
String server=null;
synchronized (pos){
if(pos>keySet.size()){
pos=0;
server=keylist.get(pos);
pos++;
}
}
return server;
}
}
2.随机算法
/**
随机算法
**/
public class Random {
public static String getServer(){
//重建一个Map,避免服务器的上下线导致的并发问题
Map<String,Integer> serverMap=new HashMap<String,Integer>();
serverMap.putAll(IpMap.serverWeightMap);
//取得Ip地址List
Set<String> keySet=serverMap.keySet();
ArrayList<String> keylist=new ArrayList<String>();
keylist.addAll(keySet);
java.util.Random ran=new java.util.Random();
int randomPos= ran.nextInt(keylist.size());
return keylist.get(randomPos);
}
}
3.源地址哈希
/**
源地址哈希
**/
public class Hash {
public static String getServer(){
Map<String,Integer> serverMap=new HashMap<String,Integer>();
serverMap.putAll(IpMap.serverWeightMap);
//取得Ip地址List
Set<String> keySet=serverMap.keySet();
ArrayList<String> keylist=new ArrayList<String>();
keylist.addAll(keySet);
//在web应用中可通过HttpServlet的getRemoteIp方法获取
String remoteIp="127.0.0.1";
int hashcode=remoteIp.hashCode();
int serverListSize=keylist.size();
int serverPos=hashcode % serverListSize;
return keylist.get(serverPos);
}
}
4.加权轮询
/**
加权轮询
**/
public class WeightRoundRobin {
private static Integer pos;
public static String getServer(){
Map<String,Integer> serverMap=new HashMap<String,Integer>();
serverMap.putAll(IpMap.serverWeightMap);
//取得Ip地址List
Set<String> keySet=serverMap.keySet();
Iterator<String>iterator=keySet.iterator();
List<String>serverList=new ArrayList<>();
while(iterator.hasNext()) {
String server = iterator.next();
int weight = serverMap.get(server);
for (int i = 0; i < weight; i++) {
serverList.add(server);
}
}
String server1=null;
synchronized (pos){
if(pos>keySet.size()){
pos=0;
server1=serverList.get(pos);
pos++;
}
return server1;
}
}
}