Zookeeper:Curator Watcher机制和事务控制
Curator提供两种Watcher来监听节点的变化。
后文中的ct:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | CuratorFramework ct; @Before public void before(){ ct = CuratorFrameworkFactory.builder() //ip:端口 .connectString( "192.168.10.132:2181,192.168.10.133:2181,192.168.10.135:2181" ) //超时时间 .sessionTimeoutMs( 5000 ) //连接断开5秒后,会进行一次重连 .retryPolicy( new RetryOneTime( 5000 )) //命名空间,该命名空间作为父节点 .namespace( "ct" ).build(); //打开连接 ct.start(); } @After public void after(){ ct.close(); } |
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(); |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· 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