ZooKeeper源码阅读——客户端负载均衡算法

  zk客户端连接、ping server端时采用了轮询算法作为负载均衡算法。每次向服务端发送ping请求时,都会调用next方法获取一个server地址,然后发送ping请求。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public InetSocketAddress next(long spinDelay) {
++currentIndex;
if (currentIndex == serverAddresses.size()) {
currentIndex = 0;
}
if (currentIndex == lastIndex && spinDelay > 0) {
try {
Thread.sleep(spinDelay);
} catch (InterruptedException e) {
LOG.warn("Unexpected exception", e);
}
} else if (lastIndex == -1) {
// We don't want to sleep on the first ever connect attempt.
lastIndex = 0;
}

return serverAddresses.get(currentIndex);
}