Operation of Zookeeper Basic API - Create Node

Synchronous creation

package com.paic.Spark;

import org.apache.zookeeper.*;

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

/**
 * Created by xlucas on 2018/4/11.
 */
public class ZookeeperDemo2 implements Watcher {
    private static CountDownLatch connectedSe=new CountDownLatch(1);
    public  static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        //构建会话
        ZooKeeper zk=new ZooKeeper("10.25.76.173", 2000, new ZookeeperDemo2());
        connectedSe.await();
        String path1=zk.create("/zk-hosts","create1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        System.out.println("sucess create path "+ path1);

        String path2=zk.create("/zk-hosts1","create2".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL_SEQUENTIAL);
        System.out.println("sucess create path"+path2);

    }
    //实现了process方法该方法负责处理来自Zookeeper服务端的watcher通知,在收到服务端发来的syncConnected事件之后
    //解除主程序在CountDownLatch上的等待阻塞,至此客户端会话创建完毕
    @Override
    public void process(WatchedEvent event) {
        System.out.println("Receive watched event"+ event);
        if(Watcher.Event.KeeperState.SyncConnected==event.getState()){
            connectedSe.countDown();
        }

    }
}

operation result:

Receive watched eventWatchedEvent state:SyncConnected type:None path:null
sucess create path /zk-hosts
sucess create path/zk-hosts10000000023

    As can be seen from the above program, using synchronization to create nodes, temporary nodes and temporary sequential nodes, it can be seen from the returned results that if a temporary node is created, the return value of PAI is the path parameter passed in at that time. If a temporary node is created Sequence node, then Zookeeper will automatically add a number to the node suffix, and return a complete node path of the data node in the return value of the PAI interface

Asynchronous creation

package com.paic.Spark;

import org.apache.zookeeper.*;

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

/**
 * Created by xlucas on 2018/4/12.
 */
public class ZookeeperDemo4 implements Watcher {
    private static CountDownLatch connectedSe=new CountDownLatch(1);
    public  static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        //构建会话
        ZooKeeper zk=new ZooKeeper("10.25.76.173", 2000, new ZookeeperDemo4());
        connectedSe.await();
        zk.create("/zk-hosts-ephemeral-","create1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL,new StringCallback(),"context");
        zk.create("/zk-hosts-ephemeral-","create1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL,new StringCallback(),"context");
        zk.create("/zk-hosts1-ephemeral-","create2".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL_SEQUENTIAL,new StringCallback(),"context");
        Thread.sleep(Integer.MAX_VALUE);
    }
    //实现了process方法该方法负责处理来自Zookeeper服务端的watcher通知,在收到服务端发来的syncConnected事件之后
    //解除主程序在CountDownLatch上的等待阻塞,至此客户端会话创建完毕
    @Override
    public void process(WatchedEvent event) {
        System.out.println("Receive watched event"+ event);
        if(Watcher.Event.KeeperState.SyncConnected==event.getState()){
            connectedSe.countDown();
        }

    }
}

package com.paic.Spark;

import org.apache.zookeeper.AsyncCallback;

/**
 * Created by xlucas on 2018/4/12.
 */
public class StringCallback implements AsyncCallback.StringCallback {
    @Override
    public void processResult(int rc, String path, Object ctx, String name) {
        System.out.println("create path result:["+ rc +", "+path +","+ctx+", real path name "+name+" ]");
    }
}

operation result

Receive watched eventWatchedEvent state:SyncConnected type:None path:null
create path result:[0, /zk-hosts-ephemeral-,context, real path name /zk-hosts-ephemeral- ]
create path result:[-110, /zk-hosts-ephemeral-,context, real path name null ]
create path result:[0, /zk-hosts1-ephemeral-,context, real path name /zk-hosts1-ephemeral-0000000029 ]

    As can be seen from this program fragment, it is also very simple to create an interface in an asynchronous way. Users only need to implement the AsyncCallback.StringCallback() interface. AsyncCallback includes ACLCallback, Children2Callback, ChildrenCallback, DataCallback, MultiCallback, StatCallback, StringCallback, VoidCallback eight There are different callback interfaces, and users can implement different interfaces in different asynchronous interfaces. The biggest difference between the synchronous interface method
and synchronous interface method is that the node creation process (including network communication and server node creation process) is asynchronous, and in the synchronous interface During the calling process, we need to pay attention to the possibility of the interface throwing exceptions, but in the asynchronous interface, the interface itself will not throw exceptions, and all exceptions will be reflected in the callback function through the Result Code (response?)

The callback function processResult(int rc, String path, Object ctx, String name) parameter description
**Rc:**Result Code Server response code, the client can identify the result of the PAI call from this response code, the response code description is
        0 : The interface call is successful
        -4: The connection between the client and the server has been disconnected
        -110: The specified node already exists
        -112: The session has expired
Path : The data node and node path parameters passed to the API when the interface is called
Ctx : The interface is passed when the interface is called Enter the ctx parameter value
Name of the API : the name of the node actually created on the server side. From the above program, we can see that when the node is created for the third time, since the node type created is a sequential node, there is no real order created on the server side. Before the node, the client cannot know the full node path of the node, so in the callback method, the server will return the full node path of the data node

Guess you like

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