Check whether the node exists after zookeeper is connected
After zookeeper is a beginner, a problem occurs to verify the impact of the cluster on a machine after the cluster is configured.
The cluster consists of three machines. One of them (IP1) is disabled through "Sh bin/zkserver. Sh stop ).
Then test in the following code:
// Create a connection zookeeper zk = new Zookeeper ("IP1: 2189, ip2: 2189, IP3: 2189", 1000, New watcher () {// monitor all triggered events @ override public void process (watchedevent event) {system. out. println ("triggered" + event. getType () + "event! ") ;}}); // Retrieve the subdirectory node list system. out. println (zk. getchildren ("/testrootpath", true); // close the connection to ZK. close ();
After testing, the following exceptions occasionally occur:
Exception in thread "main" org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /testRootPath at org.apache.zookeeper.KeeperException.create(KeeperException.java:99) at org.apache.zookeeper.KeeperException.create(KeeperException.java:51) at org.apache.zookeeper.ZooKeeper.getChildren(ZooKeeper.java:1468) at org.apache.zookeeper.ZooKeeper.getChildren(ZooKeeper.java:1496)
The above code is no problem when the cluster is completely normal.
After zookeeper is connected, the state here should be conecting. An error will be reported when verifying whether a node exists during connection. The solution is also very simple, that is, wait until the zookeeper client and fully connected to the server, the state is conected, and then perform other operations.
The modified code is as follows:
Final countdownlatch connectedsignal = new countdownlatch (1); // create a connection to the server zookeeper zk = new Zookeeper ("IP1: 2189, ip2: 2189, IP3: 2189", 1000, new watcher () {// monitor all triggered events @ override public void process (watchedevent event) {system. out. println ("triggered" + event. getType () + "event! "); If (event. getstate () = keeperstate. syncconnected) {connectedsignal. countdown (); // reciprocal-1 }}); // wait for the connection to complete connectedsignal. await (); // retrieve the list of sub-directory nodes system. out. println (zk. getchildren ("/testrootpath", true); // close the connection to ZK. close ();