参考:全网最详细的zookeeper实战教程,看完你就知道有多值 - 知乎 (zhihu.com)
ZooKeeper入门,看这篇就够了! - 知乎 (zhihu.com)
windows安装zk:windows环境下安装zookeeper教程详解(单机版)_风轩雨墨的博客-CSDN博客
zk的watch机制:Zookeeper——Watch机制原理_zookeeper watch机制_庄小焱的博客-CSDN博客
命令行使用zk:
javaAPI使用zk:
znode增删改查demo:
CRUDMain.java
package com.hmb; import org.apache.zookeeper.*; import java.io.IOException; public class CRUDMain { public static void main(String[] args) throws InterruptedException, KeeperException, IOException { String SERVER_HOST = "127.0.0.1:2181"; int SESSION_TIME_OUT = 2000; ZooKeeper zooKeeper = new ZooKeeper(SERVER_HOST, SESSION_TIME_OUT, new Watcher() { @Override public void process(WatchedEvent watchedEvent) { Event.KeeperState state = watchedEvent.getState(); if (state == Event.KeeperState.SyncConnected) { Event.EventType type = watchedEvent.getType(); if (type == Event.EventType.None) { System.out.println("zk client connect server successfully..."); } } } }); String path = "/java"; zooKeeper.create(path, "HelloWorld".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); System.out.println("add znode successfully."); System.out.println(new String(zooKeeper.getData(path, false, null))); zooKeeper.setData(path, "hhhh".getBytes(), -1); System.out.println(new String(zooKeeper.getData(path, false, null))); zooKeeper.delete(path, -1); System.out.println(zooKeeper.exists(path, false)); zooKeeper.close(); } }
运行结果:
服务器上下线动态感知demo:
ZkClient.java
package com.hmb; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooKeeper; import java.io.IOException; import java.util.LinkedList; import java.util.List; public class ZkClient { private static ZooKeeper zooKeeper; private static String path = "/"; public static void main(String[] args) throws IOException, InterruptedException, KeeperException { zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000, new Watcher() { @Override public void process(WatchedEvent event) { if (event.getType() == Event.EventType.NodeChildrenChanged && event.getPath().equals("/")) { try { showNodeList(); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (KeeperException e) { throw new RuntimeException(e); } } } }); showNodeList(); Thread.sleep(Long.MAX_VALUE); } private static void showNodeList() throws InterruptedException, KeeperException { List<String> nodeList = zooKeeper.getChildren(path, true); System.out.println("====nodeList===="); for (String node : nodeList) { System.out.println("nodeName:" + node); } } }
先运行程序,然后到客户端中增删znode,回来可见程序成功监控着“/”目录下znode的变化
标签:zooKeeper,String,demo,zookeeper,new,path,import From: https://www.cnblogs.com/hemeiwolong/p/17613041.html