【问题标题】:how to specify timeout when creating a connection to zookeeper server创建与zookeeper服务器的连接时如何指定超时
【发布时间】:2019-02-22 01:14:19
【问题描述】:

我在开发过程中使用 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 中提供的方式?

【问题讨论】:

    标签: java apache-zookeeper


    【解决方案1】:

    当一个 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 有一些限制

    当您与服务器断开连接时(例如,当服务器出现故障时),在重新建立连接之前,您将无法获得任何手表。

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

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

    【讨论】:

    • 欢呼你的回答为我解决了问题,并给了我一个我没有看到的方向的推动力。不过不要忘记支持这个问题:-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-06
    • 1970-01-01
    • 1970-01-01
    • 2016-05-08
    • 1970-01-01
    • 1970-01-01
    • 2016-06-07
    相关资源
    最近更新 更多