Curator教程(一)快速入門

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>


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語句:session

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

2.建立節點

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


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");
相關文章
相關標籤/搜索