zookeeper递归删除znode节点java Demo

因为zookeeper只允许删除叶子节点,如果要删除非叶子节点,只能使用递归,zookeeper的文件结构是树型结构,和linux的目录结构相似,所有程序和我之前写的递归删除本地文件和递归删除hdfs上的文件是差不多的,这里也分享下吧。

下面是zookeeper的存储结构示意图:

zookeeper递归删除znode节点java Demo_第1张图片

如果要删除上面方块节点,必须递归删除,圆形的叶子节点可以直接删除。

  • 1.MyWatch类
/**
 * 自定义watch类,不做任何事
 * @author LiJie
 *  */
class MyWatch implements Watcher {

    @Override
    public void process(WatchedEvent event) {
        // DO Nothing
    }

}
  • 2.主程序
package com.lijie.zk1;

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

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

/**
 * zookeeper znode递归删除
 * @author LiJie
 *
 */
public class RmrDemo {

    private static final String connectString = "hadoop01:2181,hadoop02:2181,hadoop03:2181";

    private static final int sessionTimeout = 2000;

    private static ZooKeeper zookeeper = null;

    /**
     * main函数
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {

        //调用rmr,删除所有目录
        rmr("/");
    }

    /**
     * 递归删除 因为zookeeper只允许删除叶子节点,如果要删除非叶子节点,只能使用递归
     * @param path
     * @throws IOException
     */
    public static void rmr(String path) throws Exception {
        ZooKeeper zk = getZookeeper();
        //获取路径下的节点
        List children = zk.getChildren(path, false);
        for (String pathCd : children) {
            //获取父节点下面的子节点路径
            String newPath = "";
            //递归调用,判断是否是根节点
            if (path.equals("/")) {
                newPath = "/" + pathCd;
            } else {
                newPath = path + "/" + pathCd;
            }
            rmr(newPath);
        }
        //删除节点,并过滤zookeeper节点和 /节点
        if (path != null && !path.trim().startsWith("/zookeeper") && !path.trim().equals("/")) {
            zk.delete(path, -1);
            //打印删除的节点路径
            System.out.println("被删除的节点为:" + path);
        }
    }

    /**
     * 获取Zookeeper实例
     * @return
     * @throws IOException
     */
    public static ZooKeeper getZookeeper() throws IOException {
        zookeeper = new ZooKeeper(connectString, sessionTimeout, new MyWatch());
        return zookeeper;
    }

}
  • 3.创建几个测试目录
[zk: localhost:2181(CONNECTED) 0] ls /
[zookeeper]
[zk: localhost:2181(CONNECTED) 1] create /lijie 1   
Created /lijie
[zk: localhost:2181(CONNECTED) 2] create /lijie/test1 2
Created /lijie/test1
[zk: localhost:2181(CONNECTED) 3] create /lijie/test1/test2 3
Created /lijie/test1/test2
[zk: localhost:2181(CONNECTED) 4] create /lijie/test1/test3 4
Created /lijie/test1/test3
  • 4.运行程序,查看结果

这里写图片描述

你可能感兴趣的:(zookeeper,java,zookeeper,递归,递归删除)