zookeeper JavaAPI 操作-watch监听

1.NodeCache监听代码:

@Test
public void testNodeCache() throws Exception {
    //1.创建NodeCache对象
    NodeCache nodeCache = new NodeCache(client,"/app1");
    //2.注册监听
    nodeCache.getListenable().addListener(new NodeCacheListener() {
        @Override
        public void nodeChanged() throws Exception {
            System.out.println("节点变化了");
            //获取修改节点后的数据
            byte[] data = nodeCache.getCurrentData().getData();
            System.out.println(data);
        }
    });
    //3.开启监听,如果设置为true,则开启监听是,加载缓冲数据
    nodeCache.start(true);
    while (true){

    }
}

2.pathchildrenCache监听代码:

/**
 * 演示testPathchildrenCache:监听某个节点的子节点们
 *
 * */
@Test
public void testPathchildrenCache() throws Exception {
    //1.创建监听对象
    PathChildrenCache pathChildrenCache = new PathChildrenCache(client,"/app2",true);
    //2.绑定监听器
    pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {
        @Override
        public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent pathChildrenCacheEvent) throws Exception {
            System.out.println("子节点变化了");
            System.out.println(pathChildrenCacheEvent);
            //监听子节点的数据变更,并且拿到变更后的数据
                //1.获取类型
            PathChildrenCacheEvent.Type type = pathChildrenCacheEvent.getType();
                //2.判断类型是否是update
            if (type.equals(PathChildrenCacheEvent.Type.CHILD_UPDATED)){
                System.out.println("数据变更了");
                byte[] data = pathChildrenCacheEvent.getData().getData();
                System.out.println(new String(data));

            }

        }
    });
    //3.开启
    pathChildrenCache.start();
    while (true){

    }
}

3.TreeCache:监听某个节点和所有子节点们

//演示 TreeCache :监听某个节点和自己所有的子节点们
@Test
public void testTreeCache() throws Exception{
    //1.创建监听器
    TreeCache treeCache = new TreeCache(client,"/app2");
    //2.注册监听
    treeCache.getListenable().addListener(new TreeCacheListener() {
        @Override
        public void childEvent(CuratorFramework curatorFramework, TreeCacheEvent treeCacheEvent) throws Exception {
            System.out.println("节点变化了");
            System.out.println(treeCacheEvent);
        }
    });
    //3.开启
    treeCache.start();
    while (true){
        
    }
}

 

posted @ 2023-08-04 17:43  会秃头的小白  阅读(58)  评论(0编辑  收藏  举报