1. 程式人生 > >Zookeeper客戶端API之讀取子節點內容(九)

Zookeeper客戶端API之讀取子節點內容(九)

本篇部落格介紹一下Zookeeper原聲API讀取節點內容的使用方法。

讀取節點內容方法介紹

方法

Zookeeper提供了兩個方法來獲取節點內容,同步獲取和非同步獲取:

public byte[] getData(String path, boolean watch, Stat stat)
public void getData(final String path, Watcher watcher,
            DataCallback cb, Object ctx)

引數說明

引數 說明
path 指定資料節點的路徑,獲取該節點下面的子節點
watcher 註冊在path上的Watcher。節點變更會通知會向客戶端發起通知。
stat 指定資料節點狀態資訊。傳入舊stat,方法執行過程中會將其替換為新stat物件。
watch 表示是否需要註冊一個watcher。true:註冊預設watcher,false:不需要註冊watcher
cb 註冊一個非同步回撥函式
ctx 傳遞上下文資訊

具體案例

同步方法

package com.secbro.learn;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import
java.util.concurrent.CountDownLatch; /** * 讀取節點資料 * Created by zhuzs on 2017/3/27. */ public class TestGetData implements Watcher{ private static CountDownLatch countDownLatch = new CountDownLatch(1); private static ZooKeeper zooKeeper; private static Stat stat = new Stat(); public
static void main(String[] args) throws Exception{ zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000, new TestGetData()); countDownLatch.await(); String path = "/test-get-data"; zooKeeper.create(path,"123".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); System.out.println("同步讀取節點內容:" + new String(zooKeeper.getData(path,true,stat))); System.out.println("同步讀取Stat:czxid=" + stat.getCzxid() + ";mzxid=" + stat.getMzxid() + ";version=" + stat.getVersion()); zooKeeper.setData(path,"123".getBytes(),-1); Thread.sleep(10000); } public void process(WatchedEvent event) { if (Event.KeeperState.SyncConnected == event.getState()) { if(Event.EventType.None == event.getType() && null == event.getPath()){ // 連線時的監聽事件 countDownLatch.countDown(); } else if (event.getType() == Event.EventType.NodeDataChanged){ // 子節點內容變更時的監聽 try { System.out.println("監聽獲得通知內容:data=" + new String(zooKeeper.getData(event.getPath(),true,stat))); System.out.println("監聽獲得通知Stat:czxid=" + stat.getCzxid() + ";mzxid=" + stat.getMzxid() + ";version=" + stat.getVersion()); } catch (Exception e) { e.printStackTrace(); } } } } }

執行結果:

同步讀取節點內容:123
同步讀取Stat:czxid=14700;mzxid=14700;version=0
監聽獲得通知內容:data=123
監聽獲得通知Stat:czxid=14700;mzxid=14701;version=1

程式碼的基本邏輯為建立一個臨時節點,然後讀取臨時節點內容,並註冊監聽,當節點變化(內容變化或版本資訊變化),觸發監聽事件,獲取最新的節點資訊。

非同步方法

package com.secbro.learn;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.util.concurrent.CountDownLatch;

/**
 *  讀取節點資料
 * Created by zhuzs on 2017/3/27.
 */
public class TestGetData implements Watcher{
    private static CountDownLatch countDownLatch = new CountDownLatch(1);

    private static ZooKeeper zooKeeper;
    private static Stat stat = new Stat();

    public static void main(String[] args) throws Exception{
        zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000, new TestGetData());
        countDownLatch.await();

        String path = "/test-get-data";
        zooKeeper.create(path,"123".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        // 非同步讀取節點內容
        zooKeeper.getData(path,true,new MyDataCallback(),null);

        zooKeeper.setData(path,"123".getBytes(),-1);

        Thread.sleep(10000);
    }

    public void process(WatchedEvent event) {
        if (Event.KeeperState.SyncConnected == event.getState()) {
            if(Event.EventType.None == event.getType() && null == event.getPath()){ // 連線時的監聽事件
                countDownLatch.countDown();
            } else if (event.getType() == Event.EventType.NodeDataChanged){ // 子節點內容變更時的監聽
                try {
                    System.out.println("監聽獲得通知內容:data="
                            + new String(zooKeeper.getData(event.getPath(),true,stat)));
                    System.out.println("監聽獲得通知Stat:czxid=" + stat.getCzxid()
                            + ";mzxid=" + stat.getMzxid() + ";version="  + stat.getVersion());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

class MyDataCallback implements AsyncCallback.DataCallback{

    public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
        System.out.println("非同步返回結果:rc=" + rc + ";path=" + path + ";data=" + new String(data));
        System.out.println("非同步讀取Stat:czxid=" + stat.getCzxid()
                + ";mzxid=" + stat.getMzxid() + ";version="  + stat.getVersion());
    }
}

執行結果:

非同步返回結果:rc=0;path=/test-get-data;data=123
非同步讀取Stat:czxid=14704;mzxid=14704;version=0
監聽獲得通知內容:data=123
監聽獲得通知Stat:czxid=14704;mzxid=14705;version=1

非同步方法與同步方法業務邏輯基本相同,區別點在於將同步獲取改為非同步獲取。