Operation of Zookeeper Basic API - Get Data

Obtaining data
The client can obtain the data content of a node through the Zookeeper API.

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

There are also synchronous and asynchronous interfaces,
path : the node path of the specified data node,
watcher : the registered watcher, once the content of the registered node changes, it will send a notification to the client, this parameter allows to pass in null
stat : the node of the specified data node Status information, the usage is to pass in an old stat variable in the interface, the stat variable will be replaced by the new stat object from the server response during the execution of the method.
Watch : Indicate whether a watcher needs to be registered
Cb : Register an asynchronous callback Function
Ctx : object used to pass contextual information

read data synchronously

package com.paic.Spark;

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

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * Created by Xlucas on 2018/4/16.
 */
public class ZookeeperDemo7 implements  Watcher{
    private static CountDownLatch connectedSe=new CountDownLatch(1);
    private static ZooKeeper zk=null;
    private  static Stat stat=new Stat();
    public  static void  main(String[] args) throws IOException, InterruptedException, KeeperException {
        String path="/zk-hosts-getDate";
        zk=new ZooKeeper("10.25.76.173", 2000, new ZookeeperDemo7());
        connectedSe.await();
        //创建父节点
        zk.create(path,"get1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        //获取节点数据内容
        System.out.println(new String(zk.getData(path,true,stat)));
        System.out.println(stat.getCzxid()+","+ stat.getMzxid()+","+stat.getVersion());
        zk.setData(path,"123".getBytes(),-1);
        Thread.sleep(Integer.MAX_VALUE);
    }
    @Override
    public void process(WatchedEvent event) {
        //监听路径节点下是否有变化,
        if(Watcher.Event.KeeperState.SyncConnected==event.getState()){
            if (Watcher.Event.EventType.None==event.getType()&&null ==event.getPath()){
                connectedSe.countDown();
            }else if(event.getType()== Event.EventType.NodeDataChanged){
                try{
                    System.out.println(new String(zk.getData(event.getPath(),true,stat)));
                    System.out.println(stat.getCzxid()+","+stat.getMzxid()+","+stat.getVersion());
                }catch (Exception e){

                }
            }
        }
    }
}

Running result
get1
30064782423,30064782423,0
123
30064782423,30064782424,1

        First create a node /zk-hosts-getDate, and initialize its data content as "get1", then call the synchronous interface of getData to get the data content of the /zk-hosts-getDate node, register a watcher while calling, and then we Also use "123" to update the data content of the node. At this time, since we previously registered a watcher on the node, once the data of the node changes, the Zookeeper server will send a "" "Data change" event notification, so the client can call the getData interface again to get the new data content after receiving the event notification
        . In the internal implementation of the client, the latest node state information of the data node will be obtained from the corresponding server to replace the old state of the client.
        From the above content, we can see that the Czxid is created when "30064782423" is created in "30064782424" " is updated, so the data version of the node changes from "0" to "1". From here, we can know that the change of the data content or the data version will trigger the NodeDataChanged notification of the server.

read data asynchronously

package com.paic.Spark;

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

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * Created by Xlucas on 2018/4/16.
 */
public class ZookeeperDemo8 implements Watcher {
    private static CountDownLatch connectedSe=new CountDownLatch(1);
    private static ZooKeeper zk=null;
    public  static void  main(String[] args) throws IOException, InterruptedException, KeeperException {
        String path="/zk-hosts-getDate1";
        zk=new ZooKeeper("10.25.76.173", 2000, new ZookeeperDemo8());
        connectedSe.await();
        //创建父节点
        zk.create(path,"get1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        zk.getData(path,true,new DataCallBack(),null);
        zk.setData(path,"123".getBytes(),-1);
        Thread.sleep(Integer.MAX_VALUE);
    }
    @Override
    public void process(WatchedEvent event) {
        if(Event.KeeperState.SyncConnected==event.getState()){
            if(Event.EventType.None==event.getType()&&null==event.getPath()){
                connectedSe.countDown();
            }else if(event.getType()== Event.EventType.NodeDataChanged){
                try {
                    zk.getData(event.getPath(),true,new DataCallBack(),null);
                }catch (Exception e){

                }
            }
        }
    }
}

package com.paic.Spark;

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

/**
 * Created by Xlucas on 2018/4/16.
 */
public class DataCallBack implements AsyncCallback.DataCallback {
    @Override
    public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
        System.out.println(rc+", "+path+", "+new String(data));
        System.out.println(stat.getCzxid()+", "+stat.getMzxid()+", "+stat.getVersion());
    }
}

Running result
0, /zk-hosts-getDate1, get1
30064782449, 30064782449, 0
0, /zk-hosts-getDate1, 123
30064782449, 30064782450, 1

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324517841&siteId=291194637