ZooKeeper Java API
pom.xml 依赖
root jhxxb 1.0-SNAPSHOT ../root/pom.xml 4.0.0 zookeeper org.apache.zookeeper zookeeper 3.4.14 junit junit 4.12 test org.apache.maven.plugins maven-compiler-plugin
测试代码
public class ZooKeeperTest { // 集群地址 // private String connectString = "192.168.8.138:2181,192.168.8.136:2181,192.168.8.140:2181"; private String connectString = "127.0.0.1:2181"; private int sessionTimeout = 5000; private ZooKeeper zk; @Before public void init() throws IOException { BasicConfigurator.configure(); zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() { @Override public void process(WatchedEvent event) { } }); } @After public void close() throws InterruptedException { zk.close(); } @Test public void create() throws KeeperException, InterruptedException { // 创建节点 System.out.println(zk.create("/zhongguo", "hubei".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT)); } @Test public void getChildren() throws KeeperException, InterruptedException { // 获取节点 System.out.println(zk.getChildren("/", false)); } @Test public void getData() throws KeeperException, InterruptedException { // 获取节点数据 System.out.println(new String(zk.getData("/zhongguo", false, zk.exists("/zhongguo", false)))); } @Test public void exists() throws KeeperException, InterruptedException { // 判断节点是否存在 Stat stat = zk.exists("/zhongguo", false); System.out.println(stat == null ? "not exist" : "exist"); } @Test public void setData() throws KeeperException, InterruptedException { // 修改子目录节点数据 System.out.println(zk.setData("/zhongguo", "beijing".getBytes(), -1)); } @Test public void delete() throws Exception { // 删除空节点目录 //zk.delete("/zhongguo", -1); // 删除父节点目录 rmr("/dubbo"); } /** * 递归删除,zookeeper 只允许删除叶子节点(空节点) */ public void rmr(String path) throws Exception { // 获取路径下的节点 Listchildren = 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); } }}