Curator是Netflix公司开源的一个Zookeeper客户端,与Zookeeper提供的原生客户端相比,Curator的抽象层次更高,简化了Zookeeper客户端编程。java
Maven依赖apache
<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>
CuratorFramework client = CuratorFrameworkFactory.newClient(address, new ExponentialBackoffRetry(1000, 3));
CuratorFramework client = CuratorFrameworkFactory.builder() .connectString(address) .sessionTimeoutMs(1000) .retryPolicy(retryPolicy) .build();
CuratorFramework 使用以前必须先调用编程
client.start();
完成一系列操做后,调用client.close();方法,能够使用try-finally语句:session
CuratorFramework client = CuratorFrameworkFactory.newClient(address, new ExponentialBackoffRetry(1000, 3)); try{ client.start(); ... }finally { if(client!=null) client.close(); }
a. 建立永久性节点app
client.create() .creatingParentContainersIfNeeded() .withMode(CreateMode.PERSISTENT) .withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE) .forPath(path, "hello, zk".getBytes());
b. 建立临时节点
ide
client.create().withMode(CreateMode.EPHEMERAL).forPath(path, "hello".getBytes());
byte[] buf = client.getData().forPath(path);System.out.println("get data path:"+path+", data:"+new String(buf));
client.setData().inBackground().forPath(path, "ricky".getBytes());
Stat stat = client.checkExists().forPath(path); if(stat==null){ System.out.println("exec create path:"+path); }else { System.out.println("exec getData"); }
client.delete().deletingChildrenIfNeeded().forPath("/pandora");