引入依赖
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>4.0.0</version>
</dependency>
连接ZK
CuratorFramework curatorFramework = CuratorFrameworkFactory.builder()
.connectString(CONNECTION_STR)
.sessionTimeoutMs(5000)
.retryPolicy(new ExponentialBackoffRetry(1000, 3))
.build();
curatorFramework.start();
创建节点
curatorFramework.create().
creatingParentsIfNeeded().
withMode(CreateMode.PERSISTENT).
forPath("/a/b", "test".getBytes());
修改节点
curatorFramework.setData()
.forPath("/a/b", "test2".getBytes());
删除节点
curatorFramework.delete()
.deletingChildrenIfNeeded()
.forPath("/a");
获取节点
Stat stat=new Stat();
byte[] bytes = curatorFramework.getData()
.storingStatIn(stat)
.forPath("/a");
String data = new String(bytes);
System.out.println(data);
System.out.println(stat.toString());
创建节点的时候设置权限
List<ACL> aclList=new ArrayList<>();
ACL acl=new ACL(ZooDefs.Perms.READ|ZooDefs.Perms.ADMIN, new Id("digest", DigestAuthenticationProvider.generateDigest("root:123456")));
aclList.add(acl);
curatorFramework.create().withMode(CreateMode.PERSISTENT).withACL(aclList).forPath("/a","a".getBytes());
在已有节点上添加ACL
List<ACL> aclList=new ArrayList<>();
ACL acl=new ACL(ZooDefs.Perms.READ|ZooDefs.Perms.ADMIN, new Id("digest", DigestAuthenticationProvider.generateDigest("root:123456")));
aclList.add(acl);
curatorFramework.setACL().withACL(aclList).forPath("/a");
监听当前节点
NodeCache nodeCache=new NodeCache(curatorFramework, "/watch",false);
NodeCacheListener nodeCacheListener=()->{
System.out.println("触发监听了");
System.out.println(nodeCache.getCurrentData().getPath()+"节点触发了监听");
System.out.println("触发事件节点的数据是:"+new String(nodeCache.getCurrentData().getData()));
};
nodeCache.getListenable().addListener(nodeCacheListener);
nodeCache.start();
System.in.read();
监听子节点
PathChildrenCache pathChildrenCache=new PathChildrenCache(curatorFramework, "/watch",false);
PathChildrenCacheListener pathChildrenCacheListener=(curatorFramework1,pathChildrenCacheEvent)->{
System.out.println("类型是:"+pathChildrenCacheEvent.getType());
System.out.println("触发事件节点是:"+pathChildrenCacheEvent.getData().getPath());
System.out.println("触发事件节点的数据是:"+new String(pathChildrenCacheEvent.getData().getData()));
};
pathChildrenCache.getListenable().addListener(pathChildrenCacheListener);
pathChildrenCache.start();
System.in.read();
判断节点是否存在
Stat stat = curatorFramework.checkExists().forPath("/watch1");
System.out.println(stat);