ZooKeeper教程2

删除节点

/**
* 删除节点: delete deleteall
* 1. 删除单个节点:delete().forPath("/app1");
* 2. 删除带有子节点的节点:delete().deletingChildrenIfNeeded().forPath("/app1");
* 3. 必须成功的删除:为了防止网络抖动。本质就是重试。  client.delete().guaranteed().forPath("/app2");
* 4. 回调:inBackground
* @throws Exception
*/
@Test
public void testDelete() throws Exception {
   
    // 1. 删除单个节点
    client.delete().forPath("/app1");
}
@Test
public void testDelete2() throws Exception {
   
    //2. 删除带有子节点的节点
    client.delete().deletingChildrenIfNeeded().forPath("/app4");
}
@Test
public void testDelete3() throws Exception {
   
    //3. 必须成功的删除
    client.delete().guaranteed().forPath("/app2");
}
@Test
public void testDelete4() throws Exception {
   
    //4. 回调
    client.delete().guaranteed().inBackground(new BackgroundCallback(){
   
        @Override
        public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
   
            System.out.println("我被删除了~");
            System.out.println(event);
        }
    }).forPath("/app1");
}

Watch监听概述

•ZooKeeper 允许用户在指定节点上注册一些Watcher,并且在一些特定事件触发的时候,ZooKeeper 服务端会将事件通知到感兴趣的客户端上去,该机制是 ZooKeeper 实现分布式协调服务的重要特性。

•ZooKeeper 中引入了Watcher机制来实现了发布/订阅功能能,能够让多个订阅者同时监听某一个对象,当一个对象自身状态变化时,会通知所有订阅者。

•ZooKeeper 原生支持通过注册Watcher来进行事件监听,但是其使用并不是特别方便

需要开发人员自己反复注册Watcher,比较繁琐。

•Curator引入了 Cache 来实现对 ZooKeeper 服务端事件的监听。

•ZooKeeper提供了三种Watcher:

•NodeCache : 只是监听某一个特定的节点

•PathChildrenCache : 监控一个ZNode的子节点.

•TreeCache : 可以监控整个树上的所有节点,类似于PathChildrenCache和NodeCache的组合

Watch监听-NodeCache

/**
* 演示 NodeCache:给指定一个节点注册监听器
*/
@Test
public void testNodeCache() throws Exception {
   
    //1. 创建NodeCache对象
    final NodeCache nodeCache = new NodeCache(client,"/app1");
    //2. 注册监听
   	nodeCache.getListenable().addListener(new NodeCacheListener() {
   
        @Override
        public void nodeChanged() throws Exception {
   
            System.out.println("节点变化了~");
            //获取修改节点后的数据
            byte[] data 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值