Zookeeper--Java客戶端

BtWangZhi發表於2017-12-17

1 建立會話

public class ZkService {

    private static final StringBuilder HOSTSTR = new StringBuilder();

    private static final Integer SESSION_TIMEOUT = 6000;

    private static ZooKeeper zooKeeper = null;

    static {
        HOSTSTR.append("192.168.209.136:2181,");
        HOSTSTR.append("192.168.209.137:2181,");
        HOSTSTR.append("192.168.209.138:2181");
        try {
            zooKeeper = new ZooKeeper(HOSTSTR.toString(), SESSION_TIMEOUT, null);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            if (zooKeeper != null) {
                try {
                    zooKeeper.close();
                } catch (InterruptedException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
            e.printStackTrace();
            System.err.print("連線Zookeeper失敗");
        }
    }

    public static ZooKeeper getZkService() {
        if (zooKeeper == null) {
            try {
                zooKeeper = new ZooKeeper(HOSTSTR.toString(), SESSION_TIMEOUT,
                        null);
            } catch (IOException e) {
                if (zooKeeper != null) {
                    try {
                        zooKeeper.close();
                    } catch (InterruptedException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                }
                e.printStackTrace();
                System.err.print("連線Zookeeper失敗");
            }
        }
        return zooKeeper;
    }
}

2 建立節點
建立節點分為同步和非同步,同步建立的時候需要捕獲異常,而非同步不需要,但是需要例項化一個實現StringCallBack的類,一般情況下非同步往往效能較高些。
同步建立節點:

/**
     * 同步建立節點
     */
    private static void createNodeBySynchronous() {
        ZooKeeper zkService = ZkService.getZkService();
        String actualPath = "";
        if (zkService != null) {
            try {
                actualPath = zkService.create("/test01", "test01".getBytes(),
                        Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
                System.out.println("建立的節點路徑為" + actualPath);
            } catch (KeeperException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

非同步建立節點測試的時候,建立的執行緒需要睡眠一段時間,等待回撥執行。原因未知。

    /**
     * 非同步建立節點
     */
    private static void createNodeAsynchronous() {
        ZooKeeper zkService = ZkService.getZkService();
        if (zkService != null) {
            String context = "上下文物件測試";
            zkService.create("/test02", "/test02".getBytes(),
                    Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT,
                    new MyCallBack(), context);
            //等待回撥方法執行
            try {
                Thread.sleep(5 * 1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

測試結果:
這裡寫圖片描述

建立的節點需要登入驗證

/**
     * 同步建立節點
     * @throws NoSuchAlgorithmException 
     */
    private static void createNodeBySynchronous(){
        ZooKeeper zkService = ZkService.getZkService();
        String actualPath = "";
        if (zkService != null) {
            try {               
                //建立的節點需要登入驗證
                List<ACL> acls=new ArrayList<ACL>();
                String auth = DigestAuthenticationProvider.generateDigest("tang:123123");
                Id digest=new Id("digest",auth);
                acls.add(new ACL(Perms.ALL, digest));

                actualPath = zkService.create("/test01", "test01".getBytes(),
                        acls, CreateMode.PERSISTENT);
                System.out.println("建立的節點路徑為" + actualPath);
            } catch (KeeperException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

側試
這裡寫圖片描述
引數說明:
這裡寫圖片描述
3 刪除節點

/**
     * 非同步刪除節點
     */
    public static void testDeleteNode01() {
        ZooKeeper zooKeeper = ZkService.getZkService();
        try {
            zooKeeper.delete("/test01", 0);
            System.out.println("刪除成功");
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (KeeperException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

引數說明:
這裡寫圖片描述
4 檢視子節點路徑

/**
     * 同步檢視子節點資訊
     */
    public static void testSelectNode01(){
        ZooKeeper zkService = ZkService.getZkService();
        if(zkService!=null){
            try {
                List<String> lstChildren = zkService.getChildren("/", false);
                for (String str : lstChildren) {
                    System.out.println(str);
                }
            } catch (KeeperException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

各欄位說明:
這裡寫圖片描述

5 檢視節點資訊

public static void getNodeData01() {
        ZooKeeper zkService = ZkService.getZkService();
        if (zkService != null) {
            try {
                Stat stat = new Stat();
                byte[] data = zkService.getData("/zookeeper", false, stat);
                System.out.println("節點資料=" + new String(data));
                System.out.println("節點資料長度 dataLength=" + stat.getDataLength());
            } catch (KeeperException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

6 修改資料

public static void setNodeData01() {
        ZooKeeper zkService = ZkService.getZkService();
        if (zkService != null) {
            try {
                byte[] data = "zookeeper02".getBytes();
                Stat stat = zkService.setData("/zookeeper", data, 1);
                System.out.println("修改後節點資料版本:" + stat.getVersion());
            } catch (KeeperException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

相關文章