Operation of Zookeeper basic API - read data

Read data: get the list of sub-jie points and node data

The getChildren
client can get all the child nodes of a node through the Zookeeper API,

List<String> getChildren(String path, boolean watch)
void    getChildren(String path, boolean watch, Children2Callback cb, Object ctx)
List<String>    getChildren(String path, boolean watch, Stat stat)
List<String>    getChildren(String path, Watcher watcher)
void    getChildren(String path, Watcher watcher, Children2Callback cb, Object ctx)
void    getChildren(String path, Watcher watcher, ChildrenCallback cb, Object ctx)
List<String>    getChildren(String path, Watcher watcher, Stat stat)

Here are 7 APIs including synchronous and asynchronous interfaces.
    Path : Specifies the node path of the data node.
    Watcher : Registers the watcher. Once the child node list changes after the child node is obtained, it will be sent to the client. Send notification, this parameter allows to pass in null
    Watch : indicates that a watcher needs to be registered. If this parameter is true, then the Zookeeper client will automatically use the default watcher. If it is false, it indicates that there is no need to register watcher
    Cb : register an asynchronous callback function
    Ctx : Object used to transmit context information
    Stat : Node status information of the specified data node. The usage is to pass in an old stat variable in the interface, and the stat variable will be responded by the new stat from the server during the execution of the method. object replacement

Similar to reading data and creating nodes

synchronous read

package com.paic.Spark;

import org.apache.zookeeper.*;

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

/**
 * Created by Xlucas on 2018/4/13.
 */
public class ZookeeperDemo5 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-getChild";
        zk=new ZooKeeper("10.25.76.173", 2000, new ZookeeperDemo5());
        connectedSe.await();
        //创建父节点
        zk.create(path,"get1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        //创建子节点
        zk.create(path+"/c1","get2".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);

        List<String> childrenlist=zk.getChildren(path,true);
        System.out.println(childrenlist);
        //再次创建路径
        zk.create(path+"/c2","get3".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL);
        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.NodeChildrenChanged){
                try{
                    System.out.println("getChild"+zk.getChildren(event.getPath(),true));
                }catch (Exception e){

                }
            }
        }
    }
}

operation result

[c1]
getChild[c1, c2]

    First, a parent node /zk-hosts-getChild and a child node /zk-hosts-getChild/c1 are created, and then the synchronization interface of getChildren is called to obtain all child nodes under the /zk-hosts-getChild node. Register a watcher when calling. After that, we continue to create a node /zk-hosts-getChild/c2 to the /zk-hosts-getChild node. Since we previously registered a watcher with the /zk-hosts-getChild node, once this time When a child node is created, the Zookeeper server will send a "child node change" event notification to the client, so the client can call the getChildren method again to get the new child node list after receiving the event notification
    . , from the output results, we can also see that the node list obtained by calling getChildren is the relative node path of the data node. The results we output above are c1 and c2. In fact, the complete ZNode path should be /zk -hosts-getChild/c1 and /zk-hosts-getChild/c2

Asynchronous read

package com.paic.Spark;

import org.apache.zookeeper.*;

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

/**
 * Created by Xlucas on 2018/4/13.
 */
public class ZookeeperDemo6 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-getChild1";
        zk=new ZooKeeper("10.25.76.173", 2000, new ZookeeperDemo6());
        connectedSe.await();
        //创建父节点
        zk.create(path,"get1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        //创建子节点
        zk.create(path+"/c1","get2".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);

        zk.getChildren(path,true,new GetChildred(),null);

        //再次创建路径
        zk.create(path+"/c2","get3".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL);
        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()== Watcher.Event.EventType.NodeChildrenChanged){
                try{
                    System.out.println("getChild"+zk.getChildren(event.getPath(),true));
                }catch (Exception e){

                }
            }
        }
    }
}


package com.paic.Spark;

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

import java.util.List;

/**
 * Created by Xlucas on 2018/4/13.
 */
public class GetChildred implements AsyncCallback.Children2Callback {
    @Override
    public void processResult(int rc, String path, Object ctx, List<String> childred , Stat stat) {
        System.out.println("rc: "+rc+"  path: "+path+" ctx: "+ctx+" chilred: "+childred+" stat: "+stat);
    }
}

run log

rc: 0  path: /zk-hosts-getChild1 ctx: null chilred: [c1] stat: 30064778013,30064778013,1523580253136,1523580253136,0,1,0,0,4,1,30064778014

getChild[c1, c2]

    We have made the acquisition logic of the child node list asynchronous. The asynchronous interface is usually used in such usage scenarios. When the application starts, it will obtain some configuration information, such as "machine list". These configurations are usually large and do not want to The acquisition of configuration affects the main process of the application

Guess you like

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