Zookeeper实例原生API--异步创建节点


import java.util.concurrent.CountDownLatch;
import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;

/**
 * 
* @ClassName: ZooKeeper_Create_API_ASync_Usage 
* @Description: TODO(ZooKeeper API创建节点,使用异步(async)接口。) 
* @author RongShu
* @date 2017年6月11日 下午8:29:44 
*
 */
public class ZooKeeper_Create_API_ASync_Usage implements Watcher {
    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);
    public static void main(String[] args) throws Exception{
	 ZooKeeper zookeeper = new ZooKeeper("localhost:2181",5000,new ZooKeeper_Create_API_ASync_Usage());
	 connectedSemaphore.await();
	 zookeeper.create("/zk-test-ephemeral-", "".getBytes(),Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, new IStringCallback(), "I am context.");
	 zookeeper.create("/zk-test-ephemeral-", "".getBytes(),Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL,new IStringCallback(), "I am context.");
	 zookeeper.create("/zk-test-ephemeral-", "".getBytes(),Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL,new IStringCallback(), "I am context.");
	 Thread.sleep( Integer.MAX_VALUE );
    }
    public void process(WatchedEvent event) {
        if (KeeperState.SyncConnected == event.getState()) {
            connectedSemaphore.countDown();
        }
    }
}
class IStringCallback implements AsyncCallback.StringCallback{
  public void processResult(int rc, String path, Object ctx, String name) {
    System.out.println("Create path result: [" + rc + ", " + path + ", " + ctx + ", real path name: " + name);
    }
  }

输出
Create path result: [0, /zk-test-ephemeral-, I am context., real path name: /zk-test-ephemeral-
Create path result: [-110, /zk-test-ephemeral-, I am context., real path name: null
Create path result: [0, /zk-test-ephemeral-, I am context., real path name: /zk-test-ephemeral-0000000021


注意:

AsyncCallback包含了StatCallback、DataCallback、ACLCallback、ChildrenCallback、Children2Callback、StringCallback和VoidCallback 七种不同回调接口。和同步接口最大的区别就是:节点创建过程(包括网络通信和服务端的节点创建过程)是异步的,并且在同步接口调用过程中,我们需要关注接口抛出的异常,但是在异步接口中,接口本身不会抛出异常的,所有的异常都会在回调函数中通过Result Code 来体现。


扩展


Zookeeper实例原生API--异步创建节点_第1张图片


关于API内容请参看官网或Zookeeper实例原生API--同步创建节点

参考

1.《从Paxos到Zookeeper:分布式一致性原理与实践》

2. https://zookeeper.apache.org/doc/r3.5.3-beta/api/index.html


你可能感兴趣的:(Zookeeper)