创建与 zookeeper 服务器的连接时如何指定超时

how to specify timeout when creating a connection to zookeeper server

我在开发过程中使用 ZooKeeper 已经有一段时间了,但我似乎没有明白的一件事是没有办法(至少我想不通)如何指定超时创建与 ZooKeeper 服务器的连接,例如:

ZooKeeper zoo;
        final CountDownLatch connectedSignal = new CountDownLatch(1);
        zoo = new ZooKeeper("localhost:2182", 5000, new Watcher() {

            public void process(WatchedEvent we) {
                if (we.getState() == KeeperState.SyncConnected) {
                    connectedSignal.countDown();
                }
                if (we.getState() == KeeperState.Disconnected) {
                    connectedSignal.countDown();
                }
                if (we.getType() == Event.EventType.None) {
                    connectedSignal.countDown();
                }
            }
        });
        System.out.println("in watcher");
        connectedSignal.await();

请注意,如果 ZooKeeper 服务器关闭,似乎不会发生超时,因此不会引发异常,并且我的代码始终在等待倒计时锁存器。我也试过在 zoo.cfg 中设置这个 属性 但它没有任何效果:

zookeeper.connection.timeout.ms=5000

需要帮助了解 java API 中是否提供了一些方法让 ZooKeeper 检查是否无法成功创建到 ZooKeeper 服务器的连接?请注意,我知道我们可以通过 executorservice 和 futures 来完成,但我需要 API?

中提供的方法

在创建ZooKeeper对象的同时,还会创建两个线程:IO线程和Event线程。 IO 线程将进行会话维护,例如重新连接到 ZooKeeper 服务器并维护心跳。

并且在上面的代码中,5000是会话超时值,有效!如果启用日志记录,您会发现心跳日志,

org.apache.zookeeper.ClientCnxn - Got ping response for sessionid 0x...

断开连接时

org.apache.zookeeper.ClientCnxn - Session 0x... for server null, unexpected error, closing socket connection and attempting reconnect...`

现在,我们需要知道 Watch 有一些限制

When you disconnect from a server (for example, when the server fails), you will not get any watches until the connection is reestablished.

由于在断开连接时我们无法接收到任何观察者事件,因此 connectedSignal.await() 在实践中可能有点危险。您可以尝试使用超时版本,connectedSignal.await(5000),或者等到连接恢复。

如果您想监控与 ZK 服务器的连接,您可以生成一个单独的线程,运行 zoo.getState() 定期查看当前状态。