1、轮询法(Round-Robin)
2、权重轮询(Weighted Round-Robin)
3、IP-hash
根据请求者ip的hash值 可以保证来自同一ip的请求被打到固定的机器上,可以解决session问题。
4、url_hash
根据请求的url的hash值将请求分到不同的机器中,当后台服务器为缓存的时候效率高
5、 fair
根据后台响应时间来分发请求,响应时间短的分发的请求多
轮询法代码实现
public class RoundRobinTest {
public int[] machineArr = new int[]{1,2,3,4,5};
public volatile int index = 0;
public synchronized int getMachineId() {
if (index >= 5) {
index = 0;
}
int id = machineArr[index];
index++;
return id;
}
public static void main(String[] args) {
RoundRobinTest r = new RoundRobinTest();
new Thread(()->{
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " "+r.getMachineId());
}
},"threadA").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " "+r.getMachineId());
}
},"threadB").start();
}
}