1.Spring Cloud 中的 Robin 的实现如下:
以下代码出自 ribbon-loadbalancer-2.2.2.jar 中的 RoundRobinRule 类。
private AtomicInteger nextServerCyclicCounter;
下面代码只保留了线性轮询算法的核心实现:
public Server choose(ILoadBalancer lb, Object key) { List<Server> allServers = lb.getAllServers(); int serverCount = allServers.size(); int nextServerIndex = incrementAndGetModulo(serverCount); server = allServers.get(nextServerIndex); return server; }
/** * Inspired by the implementation of {@link AtomicInteger#incrementAndGet()}. * * @param modulo The modulo to bound the value of the counter. * @return The next value. */ private int incrementAndGetModulo(int modulo) { for (;;) { int current = nextServerCyclicCounter.get(); int next = (current + 1) % modulo; if (nextServerCyclicCounter.compareAndSet(current, next)) return next; } }