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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章