本文介绍了如何检测 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?

推荐答案

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

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.

首先与curator客户端建立连接,并在所有节点上启动

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 会话何时丢失或超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 08:11