1. 程式人生 > >Curator教程(一)快速入門

Curator教程(一)快速入門

Curator是Netflix公司開源的一個Zookeeper客戶端,與Zookeeper提供的原生客戶端相比,Curator的抽象層次更高,簡化了Zookeeper客戶端程式設計。


Maven依賴

  <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.建立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");