【基於zookeeper 客戶端的Curator API 基本操作】

pom依賴
 <!-- zookeeper -->
    <dependency>
        <groupId>org.apache.zookeeper</groupId>
        <artifactId>zookeeper</artifactId>
        <version>3.4.9</version>
    </dependency>
    <!-- zk 客戶端api-->
    <dependency>
        <groupId>org.apache.curator</groupId>
        <artifactId>curator-recipes</artifactId>
        <version>4.0.1</version>
    </dependency>

組件

  • curator-framework:對zookeeper的底層api的一些封裝
  • curator-client:提供一些客戶端的操作,例如重試策略等
  • curator-recipes:封裝了一些高級特性,如:Cache事件監聽、選舉、分佈式鎖、分佈式計數器、分佈式Barrier等

基本操作

  1. create() 創建節點
  2. getData() 獲取節點
  3. getChildren() 獲取子節點信息
  4. NodeCache 註冊監聽 監聽節點值變更(重複監聽)
  5. PathChildrenCache 註冊子節點監聽(重複監聽)
  6. TreeCache 註冊監聽,監聽節點及子節點的變更 (重複監聽)
package com.zzhijian.zookeeperdemo.zk;

import lombok.extern.slf4j.Slf4j;
import org.apache.curator.CuratorZookeeperClient;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.framework.api.CuratorListener;
import org.apache.curator.framework.api.CuratorWatcher;
import org.apache.curator.framework.recipes.cache.*;
import org.apache.curator.retry.RetryNTimes;
import org.apache.zookeeper.*;

import java.util.List;

/**
 * TODO:
 *
 * @author 
 * @date: 2019-08-15 15:07
 **/
@Slf4j
public class CuratorApiDemo {

    private static String ZK_ADDRESS = "zkServer:2181,zkServer:2182,zkServer:2183";
    private static Integer SESSION_TIME_OUT_MS = 1000*10;
    private static Integer CONNECTION_TIME_OUT_MS = 1000*10*6;
    private static ZooKeeper zooKeeper;
    private static CuratorFramework curatorFramework;

    public static void main(String[] args) throws Exception{
        // 初始化客戶端
       /* initClient();
        createNode();*/
        init();
        //createNode01();
        //getNodeValue();
        //setNodeValue();
        //getNodeChildren();
        // 一次監聽
        getNodeChildCuratorListener();
        //重複監聽
        watchNodeCache();
        watchChildNodeCache();
        watchTreeNodeCache();
        Thread.sleep(1000* 60*10);
    }
    /**
     * TODO: 初始化zk客戶端
     * @author 
     * @return void
     * @version  1.0
     * @date 2019/8/15  下午3:40
     */
    public static void initClient() throws Exception{
        // 提供了重試策略
        CuratorZookeeperClient curatorZookeeperClient = new CuratorZookeeperClient(ZK_ADDRESS, SESSION_TIME_OUT_MS, CONNECTION_TIME_OUT_MS, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                log.error("事件被觸發了 --- 連接狀態:{},事件:{} ---, 在這裏我們可以做一些事情!!!",event.getState(),event.getType());
            }
        },new RetryNTimes(3,1000));
        curatorZookeeperClient.start();
        zooKeeper = curatorZookeeperClient.getZooKeeper();
    }

    public static void createNode() throws Exception{
        //zooKeeper.create("/curator-test", "node".getBytes(), ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.EPHEMERAL);
        zooKeeper.create("/curator-02", "node".getBytes(), ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
        zooKeeper.create("/curator-02/01", "node".getBytes(), ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
    }
    /**
     * TODO: 初始化
     * @param
     * @author 
     * @return void
     * @version  1.0
     * @date 2019/8/15  下午4:06
     */
    public static void init(){
        //實例化客戶端
        curatorFramework = CuratorFrameworkFactory.builder()
                .connectString(ZK_ADDRESS)
                .connectionTimeoutMs(CONNECTION_TIME_OUT_MS)
                .sessionTimeoutMs(SESSION_TIME_OUT_MS)
                .retryPolicy(new RetryNTimes(3,1000))
                .build();
        // 啓動客戶端
        curatorFramework.start();
    }
    /**
     * TODO: 創建節點
     * @param
     * @author 
     * @return void
     * @version  1.0
     * @date 2019/8/15  下午5:19
     */
    public static void createNode01(){
        try {
            curatorFramework.create()
                    .forPath("/curator06/0601");
            // acl 權限 mode 節點類型 遞歸創建節點
            curatorFramework.create()
                    .creatingParentsIfNeeded()
                    .withMode(CreateMode.EPHEMERAL)
                    .withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)
                    .forPath("/curator07/curator0701"," 測試遞歸節點內容".getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * TODO: 獲取節點信息
     * @param
     * @author 
     * @return java.lang.String
     * @version  1.0
     * @date 2019/8/15  下午5:20
     */
    public static void getNodeValue() {
        try {
            log.error(new String(curatorFramework.getData().forPath("/curator0601")));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * TODO: 獲取子節點列表(usingWatcher 一次性監聽)
     * @param
     * @author 
     * @return void
     * @version  1.0
     * @date 2019/8/15  下午5:24
     */
    public static void getNodeChildren() throws Exception{
        List<String> list = curatorFramework
                .getChildren()
                .usingWatcher(new CuratorWatcher() {
                    @Override
                    public void process(WatchedEvent watchedEvent) {
                        log.error("節點列表事件觸發了 --- 連接狀態:{},事件:{} ---, 在這裏我們可以做一些事情!!!",watchedEvent.getState(),watchedEvent.getType());
                    }
                })
               /* .usingWatcher(new Watcher() {
                    @Override
                    public void process(WatchedEvent event) {
                        log.error("節點列表事件觸發了 --- 連接狀態:{},事件:{} ---, 在這裏我們可以做一些事情!!!",event.getState(),event.getType());
                    }
                })*/
                .forPath("/curator06");
        log.error(list.toString());
    }

    /**
     * TODO: 獲取節點信息
     * @param
     * @author 
     * @return java.lang.String
     * @version  1.0
     * @date 2019/8/15  下午5:20
     */
    public static void setNodeValue() {
        try {
            log.error(String.valueOf(curatorFramework
                    .setData()
                    .forPath("/curator07","修改節點信息".getBytes())));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * TODO: 獲取子節點列表(CuratorListener 一次性監聽)
     * @param
     * @author 
     * @return void
     * @version  1.0
     * @date 2019/8/15  下午5:24
     */
    public static void getNodeChildCuratorListener() throws  Exception{
        // 註冊一個監聽器
        CuratorListener listener = new CuratorListener() {
            @Override
            public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception {
                System.out.println("監聽事件觸發,event內容爲:" + event);
            }
        };
        curatorFramework.getCuratorListenable().addListener(listener);
        // 獲取節點列表
        curatorFramework
                .getChildren()
                .inBackground()
                .forPath("/curator06");
    }
    /**
     * TODO: 監聽節點內容的變化
     * @param
     * @author 
     * @return void
     * @version  1.0
     * @date 2019/8/16  上午9:40
     */
    public static void watchNodeCache() throws Exception{
        // 創建nodeCache對象
        NodeCache nodeCache = new NodeCache(curatorFramework,"/curator06");
        // 啓動緩存
        nodeCache.start();
        if(nodeCache.getCurrentData() != null){
            log.error("節點的初始化數據爲:"+new String(nodeCache.getCurrentData().getData()));
        }else{
            log.error("節點初始化數據爲空。。。");
        }
       nodeCache.getListenable().addListener(new NodeCacheListener() {
           @Override
           public void nodeChanged() throws Exception {
               String data = new String(nodeCache.getCurrentData().getData());
               log.error("watchNodeCache-監聽節點變更---{}",data);
           }

       });
    }
    /**
     * TODO: 監聽子節點變更
     * @param
     * @author 
     * @return void
     * @version  1.0
     * @date 2019/8/16  下午4:55
     */
    public static void watchChildNodeCache() throws Exception{
        // PathChildrenCache 對象
        PathChildrenCache pathChildrenCache = new PathChildrenCache(curatorFramework,"/curator06",true);
        // 啓動緩存
        pathChildrenCache.start();
        // 增加監聽
        pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {
            @Override
            public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                log.error("watchChildNodeCache-監聽節點變更---{}",pathChildrenCache.getCurrentData());
            }
        });
    }
    /**
     * TODO: 監聽tree節點變更
     * @param
     * @author 
     * @return void
     * @version  1.0
     * @date 2019/8/16  下午5:21
     */
    public static void watchTreeNodeCache() throws Exception{
        // 創建nodeCache對象
        TreeCache treeCache = new TreeCache(curatorFramework,"/curator06");
        // 啓動緩存
        treeCache.start();
        // 增加監聽
        treeCache.getListenable().addListener(new TreeCacheListener() {
            @Override
            public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception {
                log.error("watchTreeNodeCache-監聽節點變更---{},{}",treeCache.getCurrentChildren("/curator06"),treeCache.getCurrentData("/curator06"));
            }
        });
    }

}

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