zookeeperAPI及示意图
作者:互联网
代码
public class zookeeperAPI {
/**
* 连接Zookeeper
* bigdata111 主机名(虚拟机)
* 2181 端口号
* */
private static String connectzk = "bigdata111:2181";
//时间 (毫秒)
private static int seeionTimeOut = 2000;
//创建客户端
private static ZooKeeper zkClient = null;
//运行
public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
init();
// createznode();
// exist();
// get();
}
//初始化
private static void init() throws IOException {
zkClient = new ZooKeeper(connectzk, seeionTimeOut, new Watcher() {
public void process(WatchedEvent watchedEvent) {
//收到事件通知
/**
* watchedEvent.getType() 监听类型
* watchedEvent.getPath() 监听路径
* */
System.out.println(watchedEvent.getType() + "--" + watchedEvent.getPath());
//再次启动监听器
try {
//监听路径 true开启
zkClient.getChildren("/",true);
}catch (Exception e){
e.printStackTrace();
}
}
});
}
//创建znode节点
public static void createznode() throws KeeperException, InterruptedException {
/**
*znode路径
*znode数据
*znode权限
* znode类型:持久,临时,持久有序,临时有序
* */
String znode = zkClient.create("/idea", "hello".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
System.out.println(znode);
}
//判断节点是否存在
public static void exist() throws KeeperException, InterruptedException {
//"/idea" 要判断的文件
Stat exists = zkClient.exists("/idea", true);
//"not exist" 不存在 "exist" 存在
System.out.println(exists==null?"not exist":"exist");
}
//获取子节点
public static void get() throws KeeperException, InterruptedException {
//"/" 路径下子节点
List<String> children = zkClient.getChildren("/", true);
// 使用增强for打印
for (String znode : children){
System.out.println(znode);
}
}
}
包
现在我的zookeeper客户端只有一个zookeeper
运行createznode方法
zookeeper客户端现在就有 idea 这个znode节点了
运行exist方法查看 idea 这个znode节点是否存在
获取 / 节点的值
标签:zookeeperAPI,public,exist,zkClient,static,znode,void,示意图 来源: https://blog.csdn.net/csdnwindnorth/article/details/100564886