Loading

Zookeeper:Curator Watcher机制和事务控制

Curator提供两种Watcher来监听节点的变化。

后文中的ct:

1.Node Cache

只是监听某一个特定的节点,监听节点的新增和修改

1
2
3
4
5
6
7
8
9
10
11
12
//监视某个节点的数据变化
final NodeCache nodeCache = new NodeCache(ct, "/node1");
nodeCache.start();
nodeCache.getListenable().addListener(new NodeCacheListener() {
    //节点变化时的回调方法
    public void nodeChanged() throws Exception {
        System.out.println(nodeCache.getCurrentData().getPath());
        System.out.println(new String(nodeCache.getCurrentData().getData()));
    }
});
Thread.sleep(100000);
nodeCache.close();

2.PathChildren Cache

监控一个ZNode的子节点,当一个子节点增加更新删除时。Path Cache会改变它的状态,会包含最新的子节点、数据和状态。

1
2
3
4
5
6
7
8
9
10
11
12
13
//第三个参数:事件中是否可以获取节点的数据
PathChildrenCache cache = new PathChildrenCache(ct, "/node1", true);
cache.start();
cache.getListenable().addListener(new PathChildrenCacheListener() {
    //节点变化时的回调方法
    public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
        System.out.println(event.getType());
        System.out.println(event.getData().getPath());
        System.out.println(new String(event.getData().getData()));
    }
});
Thread.sleep(100000);
cache.close();

 

3.事务

一系列操作要么全部成功,要么全部失败

1
2
3
4
5
6
7
//开启事务
ct.inTransaction()
        .create().forPath("/w","w".getBytes())
        .and()
        .delete().forPath("/zxc")
        //提交事务
        .and().commit();

  

posted @   秋风飒飒吹  阅读(879)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示