合规国际互联网加速 OSASE为企业客户提供高速稳定SD-WAN国际加速解决方案。 广告
## 一、概述 Zookeeper可以用客户端命令来操作,也可以用Java等编程语言来操作; ## 二、客户端 连接: ``` bin/zkCli.sh -server localhost:2181 ``` 使用 ls 命令来查看当前 ZooKeeper 中所包含的内容; ``` [zk: localhost:2181(CONNECTED) 0] ls / ``` 创建一个新的 znode; ``` [zk: localhost:2181(CONNECTED) 2] create /ray ``` 再次使用 ls 命令来查看现在 zookeeper 中所包含的内容; ``` [zk: localhost:2181(CONNECTED) 4] ls / ``` ![](https://img.kancloud.cn/ee/f3/eef339ce81e74c0bad7df778e17a137f_738x209.png) ## 三、代码开发 引入依赖: ``` <!-- https://mvnrepository.com/artifact/org.apache.zookeeper/zookeeper --> <dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>3.7.0</version> </dependency> ``` 实例代码: ``` private static CountDownLatch connectedSemaphore = new CountDownLatch(1); private static ZooKeeper zk = null; private static Stat stat = new Stat(); public static void main(String[] args) throws Exception { String path = "/ray"; zk = new ZooKeeper("211.149.232.36:2181", 5000, new Zk()); // 等待zk连接成功的通知 connectedSemaphore.await(); System.out.println("znode节点值是:" + new String(zk.getData(path, true, stat))); while (true) { } } public void process(WatchedEvent event) { if (KeeperState.SyncConnected == event.getState()) { if (EventType.None == event.getType() && null == event.getPath()) { connectedSemaphore.countDown(); } else if (event.getType() == EventType.NodeDataChanged) { // zk目录节点数据变化通知事件 try { System.out.println("znode节点值已经被修改:" + new String(zk.getData(event.getPath(), true, stat))); } catch (Exception e) { } } } } ``` 效果展示: 代码展示了,如果znode节点值发生变化,就被通知,并显示出来; 命令中修改节点值: ![](https://img.kancloud.cn/e7/fd/e7fdc18f9e2502a2635dfe62db570f71_1427x188.png) 代码执行效果: ![](https://img.kancloud.cn/72/69/7269c95332602d231aa5dad20cd5fb23_1409x288.png)