下面将介绍怎样使用 ZooKeeper 类来删除已存在的节点。
ZooKeeper 类使用 delete 方法删除节点,方法定义如下:
void delete(String path, int version) 删除指定路径的节点
void delete(String path, int version, AsyncCallback.VoidCallback cb, Object ctx) 异步版本
参数说明:
path - 节点路径,如:/zk/myNode
version - 节点版本信息
cb - 回调接口实例,异步版本方法触发该回调
ctx - 扩展数据,传递到回调接口内部
下面通过 /delete 节点来演示删除节点,代码如下:
package com.hxstrive.zookeeper; import org.apache.zookeeper.*; import org.apache.zookeeper.data.Stat; import org.junit.Before; import org.junit.Test; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CountDownLatch; /** * 删除节点 * @author hxstrive.com */ public class DeleteNode { private static ZooKeeper zooKeeper; @Before public void init() throws Exception { zooKeeper = new ZooKeeper("127.0.0.1:2181", 2000, new Watcher() { public void process(WatchedEvent watchedEvent) { System.out.println("触发了 " + watchedEvent.getType() + " 事件"); } }); // 如果节点不存在,则创建节点 Stat stat = zooKeeper.exists("/delete_node", false); if(null == stat) { String nodeName = zooKeeper.create("/delete_node", "init value".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); System.out.println("nodeName = " + nodeName); } } /** * 同步删除 */ @Test public void syncDemo() throws Exception { // 删除节点 zooKeeper.delete("/delete_node", -1); // 判断节点是否存在 Stat stat = zooKeeper.exists("/delete_node", false); if(null == stat) { System.out.println("删除节点成功"); } //输出: //触发了 None 事件 //nodeName = /delete_node //删除节点成功 } /** * 异步删除节点 */ @Test public void asyncDemo() throws Exception { Map<String,String> extData = new HashMap<>(); extData.put("code", "C100"); extData.put("title", "这是标题"); // 这里的 CountDownLatch 仅仅是为了能够等待 AsyncCallback.StatCallback CountDownLatch countDownLatch = new CountDownLatch(1); zooKeeper.delete("/delete_node", -1, new AsyncCallback.VoidCallback(){ /** * @param i 返回代码或调用结果。 * @param s 我们传递给异步调用的路径。 * @param o 我们传递给异步调用的上下文对象,这里是 extData 变量 */ @Override public void processResult(int i, String s, Object o) { System.out.println("i = " + i); System.out.println("s = " + s); System.out.println("o = " + o); countDownLatch.countDown(); } }, extData); countDownLatch.await(); // 判断节点是否存在 Stat stat = zooKeeper.exists("/delete_node", false); if(null == stat) { System.out.println("删除节点成功"); } //输出: //触发了 None 事件 //nodeName = /delete_node //i = 0 //s = /delete_node //o = {code=C100, title=这是标题} //删除节点成功 } }