Curator是Netflix公司开源的一个Zookeeper客户端,与Zookeeper提供的原生客户端相比,Curator的抽象层次更高,简化了Zookeeper客户端编程。


Maven依赖

  
    org.apache.zookeeper
    zookeeper
    3.4.9



  
        org.apache.curator
        curator-recipes
        2.7.0
    


1.创建Curator 连接实例(2种方式)

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语句:

CuratorFramework client = CuratorFrameworkFactory.newClient(address, new ExponentialBackoffRetry(1000, 3));
try{
    client.start();
    ...
}finally {
    if(client!=null)
        client.close();
}

2.创建节点

a. 创建永久性节点

client.create()
      .creatingParentContainersIfNeeded()
      .withMode(CreateMode.PERSISTENT)
      .withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)
      .forPath(path, "hello, zk".getBytes());

b. 创建临时节点

client.create().withMode(CreateMode.EPHEMERAL).forPath(path, "hello".getBytes());


3.获取节点值

byte[] buf = client.getData().forPath(path);System.out.println("get data path:"+path+", data:"+new String(buf));


4.设置节点值

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.删除节点

client.delete().deletingChildrenIfNeeded().forPath("/pandora");