I create "group" znode, and add "A","B","C" three children to the znode. I
want to print all children of "group" znode periodically,example below code:
public class ListGroup extends ConnectionWatcher {
private static Random random = new Random();
public void register(Watcher watcher) {
zk.register(watcher);
}
public void nodify(String groupName) throws KeeperException,
InterruptedException {
String path = "/" + groupName;
List<String> children = zk.getChildren(path, true);
}
public void list(String groupName) throws KeeperException,
InterruptedException {
String path = "/" + groupName;
try {
Stat stat = new Stat();
List<String> children = zk.getChildren(path, true);
if (children.isEmpty()) {
System.out.printf("No members in group %s\n", groupName);
}
for (String child : children) {
System.out.println(child);
}
} catch (KeeperException.NoNodeException e) {
System.out.printf("Group %s does not exist\n", groupName);
//System.exit(1);
}
}
public static void main(String[] args) throws Exception {
ListGroup listGroup = new ListGroup();
String connectString = "localhost:2181";
listGroup.connect(connectString);
listGroup.list("test");
while(true) {
try {
listGroup.list("test");
} catch(Exception e) {
e.printStackTrace();
}
TimeUnit.SECONDS.sleep(random.nextInt(10));
}
//listGroup.close();
}
}
I run the ListGroup class then It output :"A B C" information, and then I
close the zookeeper server, the ListGroup class output below exception:
org.apache.zookeeper.KeeperException$ConnectionLossException:
KeeperErrorCode = ConnectionLoss for /test
at org.apache.zookeeper.KeeperException.create(KeeperException.java:90)
at org.apache.zookeeper.KeeperException.create(KeeperException.java:42)
at org.apache.zookeeper.ZooKeeper.getChildren(ZooKeeper.java:1243)
at org.apache.zookeeper.ZooKeeper.getChildren(ZooKeeper.java:1271)
at hadoop.definitive.guide.ListGroup.list(ListGroup.java:30)
at hadoop.definitive.guide.ListGroup.main(ListGroup.java:51)
when I restart the zookeeper server, the ListGroup class continue to output
"A B C" information.
I think the session is expiry before I restart the zookeeper server, I have
two questions:
1. Why ListGroup class don't throw the SessionExpiredException.
2. I think client can automatically reconnect to server , after the
reconnection is successfull, the session whether is still valid?
thanks,
LiuLei