基本操作,create,update,delete
public static void main(String[] args) throws Exception {
CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder();
CuratorFramework curatorFramework = builder.connectString(CONNECTION_STR).
sessionTimeoutMs(5000).
retryPolicy(new ExponentialBackoffRetry(100, 3)).build();
curatorFramework.start();
createNode(curatorFramework);
}
private static void createNode(CuratorFramework curatorFramework) throws Exception {
curatorFramework.create().creatingParentContainersIfNeeded()
.withMode(CreateMode.PERSISTENT).forPath("/data/program","test".getBytes());
}
private static void updateNode(CuratorFramework curatorFramework) throws Exception {
curatorFramework.setData().forPath("/data/program","aaa".getBytes());
}
private static void deleteNode(CuratorFramework curatorFramework) throws Exception {
Stat stat=new Stat();
final String s = new String(curatorFramework.getData().storingStatIn(stat).forPath("/data/program"));
curatorFramework.delete().withVersion(stat.getVersion()).forPath("/data/program");
}
Watch
public static void main(String[] args) throws Exception {
CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder();
CuratorFramework curatorFramework = builder.connectString(CONNECTION_STR).sessionTimeoutMs(5000).retryPolicy(new ExponentialBackoffRetry(100, 3)).build();
curatorFramework.start();
addListenerWithChild(curatorFramework);
System.in.read();
}
private static void addListenerWithNode(CuratorFramework curatorFramework) throws Exception {
NodeCache nodeCache =new NodeCache(curatorFramework,"/watch",false);
NodeCacheListener nodeCacheListener= () ->{
System.out.println("receive Node Changed");
System.out.println(nodeCache.getCurrentData().getPath()+"---"+new String(nodeCache.getCurrentData().getData()));
};
nodeCache.getListenable().addListener(nodeCacheListener);
nodeCache.start();
}