一、使用官方的maven依赖:
<dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>3.4.10</version> </dependency>
代码:
ZooKeeper zooKeeper = new ZooKeeper("192.168.233.11:2182,192.168.233.11:2183,192.168.233.11:2184", 20000, new Watcher() { @Override public void process(WatchedEvent event) { String path = event.getPath(); System.out.println("path:"+path); System.out.println("state:"+event.getState()); System.out.println("type: "+event.getType()); System.out.println("wrapper: "+event.getWrapper()); } }); /** * //创建永久节点 * zooKeeper.create("/lock/pp","aaaa".getBytes(StandardCharsets.UTF_8), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); * //创建永久顺序节点 * String response = zooKeeper.create("/lock/pp", "aaaa".getBytes(StandardCharsets.UTF_8), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL); * //创建临时节点 * zooKeeper.create("/lock/temp","aaaa".getBytes(StandardCharsets.UTF_8), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); * //创建临时顺序节点 * zooKeeper.create("/lock/temp","aaaa".getBytes(StandardCharsets.UTF_8), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); * //查询节点的数据 * byte[] data = zooKeeper.getData("/lock/pp", false, null); * * //修改节点的数据 * zooKeeper.setData("/lock/pp", "bbd".getBytes(StandardCharsets.UTF_8), 0); * * //判断路径是否存在 * zooKeeper.exists("/lock/pp33", false); * //删除节点 * zooKeeper.delete("/lock",0);
//递归删除使用
ZKUtil.deleteRecursive(zk,"/lock") */ //注册事件 List<String> children = zooKeeper.getChildren("/lock/pp", new Watcher() { @Override public void process(WatchedEvent event) { System.out.println("收到回调事件。。。。。。。。。。。。。。。。。。。。"); String path = event.getPath(); System.out.println("path:" + path); System.out.println("state:" + event.getState()); System.out.println("type: " + event.getType()); System.out.println("wrapper: " + event.getWrapper()); } }); //创建子节点,触发事件 zooKeeper.create("/lock/pp/ll","aaaa".getBytes(StandardCharsets.UTF_8), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); TimeUnit.SECONDS.sleep(15);
方案二、第三方对官方依赖的封装:
<dependency> <groupId>com.101tec</groupId> <artifactId>zkclient</artifactId> <version>0.10</version> </dependency>
标签:zooKeeper,java,lock,zookeeper,System,println,out,event,客户端 From: https://www.cnblogs.com/yangxiaohui227/p/17541235.html