Nginx常用來做負(fù)載均衡,那么Nginx常見的算法都有哪些呢?
public class IpMap {
//待路由的Ip列表,Key代表Ip,Value代表該Ip的權(quán)重
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);
//權(quán)重為4
serverWeightMap.put("192.168.1.102",4);
serverWeightMap.put("192.168.1.103",1);
serverWeightMap.put("192.168.1.104",1);
//權(quán)重為3
serverWeightMap.put("192.168.1.105",3);
serverWeightMap.put("192.168.1.106",1);
//權(quán)重為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默認(rèn)的算法是輪詢算法:
即每?jī)纱握?qǐng)求,將下一次的請(qǐng)求分發(fā)給下一個(gè)服務(wù)器
/**
輪詢算法
**/
public class RoundRobin {
private static Integer pos=0;
public static String getServer(){
//重建一個(gè)Map,避免服務(wù)器的上下線導(dǎo)致的并發(fā)問題
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.隨機(jī)算法
/**
隨機(jī)算法
**/
public class Random {
public static String getServer(){
//重建一個(gè)Map,避免服務(wù)器的上下線導(dǎo)致的并發(fā)問題
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應(yīng)用中可通過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.加權(quán)輪詢
/**
加權(quán)輪詢
**/
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;
}
}
}