How to detect when Apache Zookeeper sessions are l

2019-07-26 03:45发布

问题:

Assume we have an Apache Zookeeper quorum up and running and n client nodes connected (using Apache Curator). Is it possible to receive notifications on one of the nodes (the one we are observing) from zookeeper when any of the other nodes sessions are terminated or a timeout is reached? If so, how is this accomplished?

回答1:

The answer is fairly simple and can be accomplished using Ephemeral nodes and PathChildrenCache. Zookeeper will detect when a node times out (in this example we set the timeout to 10s) and the associated ephemeral node will disappear from the tree. This will fire off an event which we can listen for.

First establish a connection with the curator client and start it up on all nodes

CuratorFramework curator =
    CuratorFrameworkFactory
        .newClient(zkConnectionString, 10000, 10000, retryPolicy);

curator.start();
curator.getZookeeperClient().blockUntilConnectedOrTimedOut();

Next use PathChildrenCache to assign listeners for zookeeper events. Event types include CHILD_ADDED, CHILD_UPDATED, and CHILD_REMOVED. The event object in the callback will contain the relevant information (and possible associated payload) of the node which went down.

PathChildrenCache pathCache = new PathChildrenCache(curator, "/nodes", true);
pathCache
    .getListenable()
    .addListener((curator, event) -> {
        if (event.getType() == Type.CHILD_REMOVED) {
            System.out.println("Child has been removed");
        }
    });
pathCache.start();

Now on a remote node, add the ephemeral node (here we give it an ID of 33 without a payload)

curator
    .create()
    .creatingParentsIfNeeded()
    .withMode(CreateMode.EPHEMERAL)
    .forPath("/nodes/33");

Now pull the plug on the remote node and the event should be detected where the listeners have been assigned.