如何检测Apache Zookeeper会话何时丢失或超时? [英] How to detect when Apache Zookeeper sessions are lost or timed out?

查看:114
本文介绍了如何检测Apache Zookeeper会话何时丢失或超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们已经启动并运行了Apache Zookeeper仲裁,并且连接了 n 个客户端节点(使用Apache Curator).当其他任何一个节点的会话终止或达到超时时,是否可以从zookeeper接收到其中一个节点(我们正在观察的节点)的通知?如果是这样,这是如何完成的?

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?

推荐答案

答案非常简单,可以使用临时节点和PathChildrenCache来完成. Zookeeper将检测节点何时超时(在本示例中,我们将超时设置为10s),并且关联的临时节点将从树中消失.这将触发一个我们可以收听的事件.

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

接下来,使用PathChildrenCache为Zookeeper事件分配侦听器.事件类型包括CHILD_ADDED,CHILD_UPDATED和CHILD_REMOVED.回调中的事件对象将包含发生故障的节点的相关信息(以及可能的关联有效负载).

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

现在在远程节点上,添加临时节点(此处我们给它的ID为33,没有有效载荷)

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.

这篇关于如何检测Apache Zookeeper会话何时丢失或超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆