How to detect when Apache Zookeeper sessions are lost or timed out?

时光毁灭记忆、已成空白 提交于 2019-12-11 04:47:38

问题


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.



来源:https://stackoverflow.com/questions/42539891/how-to-detect-when-apache-zookeeper-sessions-are-lost-or-timed-out

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!