最近在看spring-cloud相关模块源码,刚好看到了ribbon负载均衡的各种策略实现,今天我们看下轮询算法是如何实现的。Talk is cheap. Show me the code.
public class RoundRobinTest {
private static AtomicInteger nextServerCyclicCounter = new AtomicInteger(0);
private static int incrementAndGetModulo(int modulo) {
for (;;) {
int current = nextServerCyclicCounter.get();
int next = (current + 1) % modulo;
if (nextServerCyclicCounter.compareAndSet(current, next)) {
return next;
}
}
}
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(10);
for (int i = 0; i < 30; i++) {
executorService.execute(() -> {
System.out.print(incrementAndGetModulo(10));
});
}
}
}
//运行结果:123456780945678901234567231890
核心方法:incrementAndGetModulo(), 比如module参数是服务节点的数量,比如10,那么这个方法会轮询返回0~9,这样就可以指定去调用某个服务了,实现逻辑短小精悍!