zookeeper学习笔记--删除节点

1:删除节点API

同步方式

public void delete(final String path, int version)

异步方式

public void delete(final String path, int version, voidCallback cb, Object ctx)

  • 必须先删除叶子节点,才能再删除根节点

2:参数说明

path

指定数据节点的节点路径

version

指定节点的数据版本,即表明本次删除操作是针对该数据版本进行的,-1代表任何版本

cb

注册一个异步回调函数

ctx

用于传递上下文信息的对象

3:代码样例

package LearningZK;

import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.*;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;

public class UsingZookeeperAPI implements Watcher{

    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);

    public static void main(String[] args) throws Exception{

        /*使用ZK构造方法实例化ZK对象来建立会话*/
        /*new UsingZookeeperAPI 实现watcher接口,重写process方法,处理服务端返回的异步通知*/
        ZooKeeper zookeeper = new ZooKeeper("172.21.10.136:2181",
                5000,
                new UsingZookeeperAPI());

        System.out.println(zookeeper.getState());
//        long sessionID = zookeeper.getSessionId();     //获取会话ID
//        byte[] sessionPasswd = zookeeper.getSessionPasswd(); //获取会话密钥
        try {
            connectedSemaphore.await();
        } catch (InterruptedException e) {}
        System.out.println("ZooKeeper session established.");

        /*以同步的方式创建ZK临时节点*/
        String path1 = zookeeper.create("/ZK_test", "".getBytes(),Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        System.out.println("Create Znode Success:"+path1);

        /*以同步的方式创建ZK临时顺序节点*/
        String path2 = zookeeper.create("/ZK_test","".getBytes(),Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL_SEQUENTIAL);
        System.out.println("Create Znode Succsess:"+path2);

        /*以异步的方式创建ZK临时节点*/
        zookeeper.create("/ZK_test_async", "".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, new AsyncCallBack(), "I am content");

        /*以同步的方式删除ZK节点*/
        zookeeper.delete("/ZK_test", -1);  //-1表示任何版本
        System.out.println("Delete Znode Success");

        /*以异步的方式删除ZK节点*/
        //zookeeper.delete("/ZK_test",-1,new IsCallback(),"content");


        Thread.sleep(Integer.MAX_VALUE);
    }

    /*处理ZK服务端watcher通知,再接收到服务端发来的SyncConnected通知后,解除主程序的等待阻塞*/
    public void process(WatchedEvent event) {
        System.out.println("Receive watched event:" + event);
        if (KeeperState.SyncConnected == event.getState()) {
            connectedSemaphore.countDown();
        }
    }
}

/*异步创建节点回调方法简单实现*/
class AsyncCallBack 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);
    }
}

/*异步删除节点回调方法简单实现*/
class IsCallback implements AsyncCallback.VoidCallback{
    public void processResult(int rc, String path, Object ctx){
        System.out.println("rc:"+rc+"path:"+path+"Object:"+ctx);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_35723073/article/details/81274734