zk
1.连接对象创建
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public static void main(String[] args) { CuratorFramework 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(); //是否连接成功 System.out.println(ct.isStarted()); //关闭连接 ct.close(); } |
重连策略:
RetryOneTime(int sleepMsBetweenRetry):只重连一次
RetryNTimes(int n, int sleepMsBetweenRetries):重连n次
RetryUntilElapsed(int maxElapsedTimeMs, int sleepMsBetweenRetries):每sleepMsBetweenRetries毫秒重连一次,总等待时间超过maxElapsedTimeMs毫秒后停止重连
ExponentialBackoffRetry(int baseSleepTimeMs, int maxRetries):重连maxRetries次,重连间隔基于baseSleepTimeMs计算
计算公式如下:baseSleepTimeMs*Math.max(1,random.nextInt(1<<(retryCount+1)))。
2.创建节点
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | ct.create() //节点类型 .withMode(CreateMode.PERSISTENT) //节点权限 .withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE) //节点路径和数据 .forPath( "/node1" , "node1" .getBytes()); 支持递归创建节点 ct.create() //父节点不存在则创建 .creatingParentsIfNeeded() //节点类型 .withMode(CreateMode.PERSISTENT) //节点权限 .withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE) //节点路径和数据 .forPath( "/node2/node2" , "node2" .getBytes()); 异步方式创建(删除、更新、查询省略): ct.create() //父节点不存在则创建 .creatingParentsIfNeeded() //节点类型 .withMode(CreateMode.PERSISTENT) //节点权限 .withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE) //异步回调 .inBackground( new BackgroundCallback() { public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { System.out.println(event.getPath()+ ":" +event.getType()); } }) //节点路径和数据 .forPath( "node3" , "node3" .getBytes()); |
3.更新节点
1 | ct.setData().withVersion(- 1 ).forPath( "/node3" , "node33" .getBytes()); |
4.删除节点
1 2 3 4 5 6 7 | ct.delete().withVersion(- 1 ).forPath( "/node3" ); 删除包含子节点的节点 //递归删除 ct.delete() .deletingChildrenIfNeeded() .withVersion(- 1 ).forPath( "/node2" ); |
5.查询节点
1 2 3 4 5 6 7 8 9 10 | //查询 byte [] bytes = ct.getData().forPath( "/node1" ); System.out.println( new String(bytes)); 读取属性: Stat stat = new Stat(); byte [] bytes = ct.getData() .storingStatIn(stat).forPath( "/node1" ); System.out.println( new String(bytes)); System.out.println(stat); |
6.查询子节点数据
1 2 3 4 5 | // /ct/node1/node2 List<String> list = ct.getChildren().forPath( "/node1" ); for (String s : list) { System.out.println(s); } |
7.判断节点是否存在
1 2 | //如果节点不存在,则返回值为null Stat stat = ct.checkExists().forPath( "/node11" ); |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)