how to specify timeout when creating a connection to zookeeper server

JayD :

I have been using ZooKeeper for some time now in my development but one thing I don't seem to get is that there is no way (at least I couldn't figure it out) how to specify a timeout while creating a connection to a ZooKeeper server for example:

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();

Note that no timeout seems to occur if the ZooKeeper server is down and hence no exception is thrown and my code always keeps waiting for the countdown latch. I have tried setting this property in zoo.cfg also but it doesn't takes any effect:

zookeeper.connection.timeout.ms=5000

Need help as to whether there is some way provided in java API for ZooKeeper to check if a successful connection cannot be created to a ZooKeeper server? Note, I know we can do it via executorservice and futures but I need a way provided in the API?

Jacky :

When a ZooKeeper object is created, it will also create two threads: IO thread, and Event thread. The IO thread will do session maintenance such as reconnecting to ZooKeeper servers and maintaining heartbeat.

And in the above code, 5000 is the session timeout value, it works! If you enable logging, you will find heartbeat logs,

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

and while disconnected

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

And now, we need to know that Watch has some limitations

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

As we could not receive any watcher event while disconnected, the connectedSignal.await() might be a little dangerous in practice. You could try use a timed-out version, connectedSignal.await(5000) instead, or you would wait until the connection recovery.

And if you want to monitor the connection to ZK server, you could spawn a separate thread, run zoo.getState() periodically to see the current state.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=152126&siteId=1