编程思维训练
1、级联查看某节点下所有节点及节点值
2、删除一个节点,不管有有没有任何子节点
3、级联创建任意节点
4、清空子节点
package HomeWork;
import java.util.List;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
/**
* 编程思维训练
* 1、级联查看某节点下所有节点及节点值、、已完成
* 2、删除一个节点,不管有有没有任何子节点 、、已完成
* 3、级联创建任意节点
* 4、清空子节点
*/
public class HomeWork {
private static final String CONNECTION_STRING="hadoop02:2199,hadoop03:2199";
private static final int SESSION_TIMEOUT=5000;
public static void main(String[] args) throws Exception {
ZooKeeper zk=new ZooKeeper(CONNECTION_STRING, SESSION_TIMEOUT, null);
String path1="/demo1/watch/a";
String path2="/demo1/watch/a/d";
String path3="/demo1/watch/a/c";
if(zk.exists(path1, false)==null){
zk.create("/demo1/watch/a", "".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
if(zk.exists(path2, false)==null){
zk.create("/demo1/watch/a/d", "".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
if(zk.exists(path3, false)==null){
zk.create("/demo1/watch/a/c", "".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
/*List<String> children = zk.getChildren("/", null);
for(String c:children){
System.out.println(c);
}*/
//getChildren(zk, "/demo1");
//delete(zk, "/VIVO");
createAll(zk, "/VIVO/OPPO/XIAOMI/OPPO/XIAOMI/OPPO/XIAOMI/OPPO/XIAOMI");
Thread.sleep(5000);
cleanSon(zk, "/VIVO","/VIVO");
}
//循环获取子节点
public static void getChildren(ZooKeeper zk,String path) throws Exception {
List<String> children = zk.getChildren(path, null);
for(String c:children){
System.out.println(path+"/"+c);
if(zk.exists(path+"/"+c, false)!=null){
getChildren(zk,path+"/"+c);
}
}
}
//删除子节点 不论是不是空的
public static void delete(ZooKeeper zk,String path) throws Exception {
List<String> children = zk.getChildren(path, null);
if(children.size()!=0){
for(String c:children){
System.out.println(path+"/"+c);
if(zk.exists(path+"/"+c, false)!=null){
delete(zk,path+"/"+c);
}
}
}
System.out.println("执行删除");
zk.delete(path, -1);
}
public static void createAll(ZooKeeper zk,String path) throws Exception {//例如传入一个目录/aa/bb/cc 需要做到级联创建
//假设path=/
//假设path=/aa/bb/cc
if(!path.substring(0,1).equals("/")){
System.out.println("路径输入错误");
}
String []str=path.split("/");
// /aa/bb/cc
String sum="";//
for(int i=0;i<str.length-1;i++){// /vivo 1 /oppo 2 /xiaomi 3
sum+="/"+str[i+1];
if(zk.exists(sum, false)!=null){//第一个目录存在
}
else{
zk.create(sum, "".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
System.out.println(sum);
}
}
public static void cleanSon(ZooKeeper zk,String path,String tar) throws Exception {// /vivo
//循环遍历是否有子节点
List<String> children = zk.getChildren(path, false);
if(children.size()==0){
zk.delete(path, -1);
String[] arr=path.split("/");
String sum="";
for(int i=1;i<arr.length-1;i++){
sum+="/"+arr[i];
}
String parentPath=sum;
if(parentPath.equals(tar)){
return;
}
cleanSon(zk, parentPath,tar);
}else{
for(String c:children){
String currentPath=path+"/"+c;
cleanSon(zk, currentPath,tar);
}
}
}
}