说明
参考Ribbon
依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<version>2.0.1.RELEASE</version>
</dependency>
轮询
参考Ribbon 代码
代码位置:
com.netflix.loadbalancer.RoundRobinRule
demo
//轮询
public static void roundRule() {
List<String> serverList = new ArrayList<>();
serverList.add("1");
serverList.add("2");
serverList.add("3");
AtomicInteger atomicInteger = new AtomicInteger(0);
int len = serverList.size();
int curr = atomicInteger.get();
int next = (curr + 1) % len;
if(atomicInteger.compareAndSet(curr, next)) {
System.out.println(serverList.get(curr));
return;
}
Thread.yield();//进入就绪队列
}
随机
参考Ribbon代码
代码位置
com.netflix.loadbalancer.RandomRule
demo
//随机
public static void randomRule() {
List<String> serverList = new ArrayList<>();
serverList.add("1");
serverList.add("2");
serverList.add("3");
Random rand = new Random();
int len = serverList.size();
System.out.println(rand.nextInt(len));
}
ip哈希
demo①
//ip哈希
public static void iphashRule() {
List<String> serverList = new ArrayList<>();
serverList.add("1");
serverList.add("2");
serverList.add("3");
int mask = 0x8fffffff; //01111111 11111111 11111111 11111111 --ip哈希后有可能是负数
String ip = null;
int len = serverList.size();
ip = UUID.randomUUID().toString();
int index = (ip.hashCode() & mask) % len;
System.out.println(index);
}
demo②
//ip哈希 -- 求余时,令被除数没那么大
public static void iphashRule2() {
List<String> serverList = new ArrayList<>();
serverList.add("1");
serverList.add("2");
serverList.add("3");
int mask = 0;
String ip = null;
int len = serverList.size();
int tmp = len;
while(tmp > 0) {
mask = (mask << 1) + 1;
tmp = tmp >> 1;
}
ip = UUID.randomUUID().toString();
int index = ip.hashCode() & mask;
index = index >= len ? (index - len) : index;
System.out.println(index);
}