0 课程地址
https://coding.imooc.com/lesson/201.html#mid=12726
1 重点关注
1.1 本节内容
判断zk节点是否存在demo
1.2 关键代码
/** * 参数: * path:节点路径 * watch:watch事件 */ Stat stat = zkServer.getZookeeper().exists("/imooc-fake", true); if (stat != null) { System.out.println("查询的节点版本为dataVersion:" + stat.getVersion()); } else { System.out.println("该节点不存在..."); }
//本类watch事件,process,本类实现watcher public Stat exists(String path, boolean watch); //其他类watch事件,process。其他类实现Watcher public Stat exists(final String path, Watcher watcher) //本类watch事件,process,本类实现watcher,回调函数 public void exists(String path, boolean watch, StatCallback cb, Object ctx); //其他类watch事件,process。其他类实现Watcher,回调函数 public void exists(final String path, Watcher watcher, StatCallback cb, Object ctx);
2 课程内容
3 Coding
3.1 判断zk节点是否存在
- 启动服务端
进入到
cd /usr/local/zookeeper/bin
重启zookeeper服务端
./zkServer.sh restart
- 主类
package com.imooc.zk.demo; import java.io.IOException; import java.util.concurrent.CountDownLatch; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.Watcher.Event.EventType; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.data.Stat; /** * @Description: zookeeper 判断阶段是否存在demo */ public class ZKNodeExist implements Watcher { private ZooKeeper zookeeper = null; public static final String zkServerPath = "172.26.139.4:2181"; public static final Integer timeout = 5000; public ZKNodeExist() {} public ZKNodeExist(String connectString) { try { zookeeper = new ZooKeeper(connectString, timeout, new ZKNodeExist()); } catch (IOException e) { e.printStackTrace(); if (zookeeper != null) { try { zookeeper.close(); } catch (InterruptedException e1) { e1.printStackTrace(); } } } } private static CountDownLatch countDown = new CountDownLatch(1); public static void main(String[] args) throws Exception { ZKNodeExist zkServer = new ZKNodeExist(zkServerPath); /** * 参数: * path:节点路径 * watch:watch */ Stat stat = zkServer.getZookeeper().exists("/imooc-fake", true); if (stat != null) { System.out.println("查询的节点版本为dataVersion:" + stat.getVersion()); } else { System.out.println("该节点不存在..."); } countDown.await(); } @Override public void process(WatchedEvent event) { if (event.getType() == EventType.NodeCreated) { System.out.println("节点创建"); countDown.countDown(); } else if (event.getType() == EventType.NodeDataChanged) { System.out.println("节点数据改变"); countDown.countDown(); } else if (event.getType() == EventType.NodeDeleted) { System.out.println("节点删除"); countDown.countDown(); } } public ZooKeeper getZookeeper() { return zookeeper; } public void setZookeeper(ZooKeeper zookeeper) { this.zookeeper = zookeeper; } }
- 打印日志1(暂停状态,等待创建节点)
该节点不存在...
- linux客户端创建节点
--启动客户端 zkCli.sh [zk: localhost:2181(CONNECTED) 0] ls / [imooc2, names, zookeeper, imooc3, imooc, testnode, imooc5] [zk: localhost:2181(CONNECTED) 1] create /imooc-fake 555 Created /imooc-fake [zk: localhost:2181(CONNECTED) 2]
- 打印日志2
该节点不存在...
节点创建
诸葛