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");