CuratorFramework节点监听一 PathChildrenCache

本文介绍了CuratorFramework的PathChildrenCache节点监听特性,包括其永久监听节点及其子节点变化的特点,以及如何设置监听器。通过示例展示了监听器的使用方法,并提到了与Spring集成的配置技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

节点监听

一. PathChildrenCache

特点:

(1)永久监听指定节点下的节点
(2)只能监听指定节点下一级节点的变化,比如说指定节点”/example”, 在下面添加”node1”可以监听到,但是添加”node1/n1”就不能被监听到了
(3)可以监听到的事件:节点创建、节点数据的变化、节点删除等

使用方式

(1)创建curatorframework的client
(2)添加PathChildrenCache
(3)启动client 和 pathChildrenCache
(4)注册监听器

例子:

package cache;

import com.google.common.collect.Lists;
import discovery.ExampleServer;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.*;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.utils.CloseableUtils;
import org.apache.curator.utils.ZKPaths;
import org.apache.zookeeper.KeeperException;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;

/**
 * An example of the PathChildrenCache. The example "harness" is a command processor
 * that allows adding/updating/removed nodes in a path. A PathChildrenCache keeps a
 * cache of these changes and outputs when updates occurs.
 */
public class PathCacheExample {
   
    private static final String PATH = "/mq_monitor";
    static CuratorFramework client = CuratorFrameworkFactory.newClient("192.168.27.55", new ExponentialBackoffRetry(1000, 3));
    static PathChildrenCache pathChildrenCache = new PathChildrenCache(client, PATH, true);
    public static void main(String[] args) throws Exception {
        start();
    }

    public static void start() {
        try {
            client.start();
            pathChildrenCache.start();
            addPathChildListener(pathChildrenCache);
            processCommands(client, pathChildrenCache);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void shutdown() {
        CloseableUtils.closeQuietly(pathChildrenCache);
        CloseableUtils.closeQuietly(client);
    }

    private static void addPathChildListener(PathChildrenCache cache) {
        // a PathChildrenCacheListener is optional. Here, it's used just to log changes
        PathChildrenCacheListener listener = new PathChildrenCacheListener() {
            @Override
            public void
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值