Curator It is an open-source Zookeeper client of Netflix. Compared with the native client provided by Zookeeper, the cursor has a higher level of abstraction and simplifies the programming of Zookeeper client.
Maven dependence
<dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>3.4.9</version> </dependency> <dependency> <groupId>org.apache.curator</groupId> <artifactId>curator-recipes</artifactId> <version>2.7.0</version> </dependency>
1. Create a cursor connection instance (2 ways)
CuratorFramework client = CuratorFrameworkFactory.newClient(address, new ExponentialBackoffRetry(1000, 3));
CuratorFramework client = CuratorFrameworkFactory.builder() .connectString(address) .sessionTimeoutMs(1000) .retryPolicy(retryPolicy) .build();
The CuratorFramework must be called before it can be used
client.start();
After a series of operations, call client.close(); method, and try finally statement can be used:
CuratorFramework client = CuratorFrameworkFactory.newClient(address, new ExponentialBackoffRetry(1000, 3)); try{ client.start(); ... }finally { if(client!=null) client.close(); }
2. Create node
A. create a permanent node
client.create() .creatingParentContainersIfNeeded() .withMode(CreateMode.PERSISTENT) .withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE) .forPath(path, "hello, zk".getBytes());
b. create a temporary node
client.create().withMode(CreateMode.EPHEMERAL).forPath(path, "hello".getBytes());
3. Get node value
byte[] buf = client.getData().forPath(path);System.out.println("get data path:"+path+", data:"+new String(buf));
4. Set node value
client.setData().inBackground().forPath(path, "ricky".getBytes());
5.checkExists
Stat stat = client.checkExists().forPath(path); if(stat==null){ System.out.println("exec create path:"+path); }else { System.out.println("exec getData"); }
6. Delete node
client.delete().deletingChildrenIfNeeded().forPath("/pandora");