在之前一个文章《ZooKeeper Java API 使用样例》中提到,客户端使用ZooKeeper的时候,首先会建立与ZooKeeper的连接,方法是通过调用下面这个构造方法来实现的。
- public ZooKeeper(String connectString, //
- int sessionTimeout, //
- Watcher watcher,//
- boolean canBeReadOnly )
- throws IOException
- 192.168.1.1:2181,192.168.1.2:2181,192.168.1.3:2181
- new ZooKeeper(“192.168.1.1:2181,192.168.1.2:2181,192.168.1.3:2181”,...)
- ConnectStringParser connectStringParser =
new ConnectStringParser(“192.168.1.1:2181,192.168.1.2:2181,192.168.1.3:2181”);
- public final class ConnectStringParser {
- private final String chrootPath;
- private final ArrayList<InetSocketAddress> serverAddresses = new ArrayList<InetSocketAddress>();
- }
- public StaticHostProvider(Collection<InetSocketAddress> serverAddresses)
- throws UnknownHostException {
- ……
- ……
- Collections.shuffle(this.serverAddresses);
- }
- public InetSocketAddress next(long spinDelay) {
- ++currentIndex;
- if (currentIndex == serverAddresses.size()) {
- currentIndex = 0;
- }
- ……
- ……
- return serverAddresses.get(currentIndex);
- }