gpt4 book ai didi

java - 如何检测 Apache Zookeeper session 何时丢失或超时?

转载 作者:行者123 更新时间:2023-11-30 06:52:09 26 4
gpt4 key购买 nike

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

最佳答案

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

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

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

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

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

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,没有负载)

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

现在拔掉远程节点上的插头,应该在分配监听器的位置检测到事件。

关于java - 如何检测 Apache Zookeeper session 何时丢失或超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42539891/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com