0 课程地址
https://coding.imooc.com/lesson/201.html#mid=12732
1 重点关注
1.1 本节内容
使用curator递归创建节点
1.2 关键代码
//creatingParentsIfNeeded递归创建节点 //withMode 节点类型,永久or临时 //withACL 权限anyworld //path 路径 ,前边加上工作空间 namespace String nodePath = "/super/imooc"; byte[] data = "superme".getBytes(); cto.client.create().creatingParentsIfNeeded() .withMode(CreateMode.PERSISTENT) .withACL(Ids.OPEN_ACL_UNSAFE) .forPath(nodePath, data); create(){ client = CuratorFrameworkFactory.builder() .connectString(zkServerPath) .sessionTimeoutMs(10000).retryPolicy(retryPolicy) .namespace("workspace").build(); }
2 课程内容
3 Coding
3.1 Curator创建节点
- 启动服务端
进入到
cd /usr/local/zookeeper/bin
重启zookeeper服务端
./zkServer.sh restart
- 主类
package com.imooc.curator; import java.util.List; import org.apache.curator.RetryPolicy; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.recipes.cache.ChildData; import org.apache.curator.framework.recipes.cache.PathChildrenCache; import org.apache.curator.framework.recipes.cache.PathChildrenCache.StartMode; import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent; import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener; import org.apache.curator.retry.RetryNTimes; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.ZooDefs.Ids; public class CuratorOperator { public CuratorFramework client = null; public static final String zkServerPath = "172.26.139.4:2181"; /** * 实例化zk客户端 */ public CuratorOperator() { /** * 同步创建zk示例,原生api是异步的 * * curator链接zookeeper的策略:ExponentialBackoffRetry * baseSleepTimeMs:初始sleep的时间 * maxRetries:最大重试次数 * maxSleepMs:最大重试时间 */ // RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 5); /** * curator链接zookeeper的策略:RetryNTimes * n:重试的次数 * sleepMsBetweenRetries:每次重试间隔的时间 */ RetryPolicy retryPolicy = new RetryNTimes(3, 5000); /** * curator链接zookeeper的策略:RetryOneTime * sleepMsBetweenRetry:每次重试间隔的时间 */ // RetryPolicy retryPolicy2 = new RetryOneTime(3000); /** * 永远重试,不推荐使用 */ // RetryPolicy retryPolicy3 = new RetryForever(retryIntervalMs) /** * curator链接zookeeper的策略:RetryUntilElapsed * maxElapsedTimeMs:最大重试时间 * sleepMsBetweenRetries:每次重试间隔 * 重试时间超过maxElapsedTimeMs后,就不再重试 */ // RetryPolicy retryPolicy4 = new RetryUntilElapsed(2000, 3000); client = CuratorFrameworkFactory.builder() .connectString(zkServerPath) .sessionTimeoutMs(10000).retryPolicy(retryPolicy) .namespace("workspace").build(); client.start(); } /** * * @Description: 关闭zk客户端连接 */ public void closeZKClient() { if (client != null) { this.client.close(); } } public static void main(String[] args) throws Exception { // 实例化 CuratorOperator cto = new CuratorOperator(); boolean isZkCuratorStarted = cto.client.isStarted(); System.out.println("当前客户的状态:" + (isZkCuratorStarted ? "连接中" : "已关闭")); // 创建节点 String nodePath = "/super/imooc"; byte[] data = "superme".getBytes(); cto.client.create().creatingParentsIfNeeded() .withMode(CreateMode.PERSISTENT) .withACL(Ids.OPEN_ACL_UNSAFE) .forPath(nodePath, data); // 更新节点数据 // byte[] newData = "batman".getBytes(); // cto.client.setData().withVersion(0).forPath(nodePath, newData); // 删除节点 // cto.client.delete() // .guaranteed() // 如果删除失败,那么在后端还是继续会删除,直到成功 // .deletingChildrenIfNeeded() // 如果有子节点,就删除 // .withVersion(0) // .forPath(nodePath); // 读取节点数据 // Stat stat = new Stat(); // byte[] data = cto.client.getData().storingStatIn(stat).forPath(nodePath); // System.out.println("节点" + nodePath + "的数据为: " + new String(data)); // System.out.println("该节点的版本号为: " + stat.getVersion()); // 查询子节点 // List<String> childNodes = cto.client.getChildren() // .forPath(nodePath); // System.out.println("开始打印子节点:"); // for (String s : childNodes) { // System.out.println(s); // } // 判断节点是否存在,如果不存在则为空 // Stat statExist = cto.client.checkExists().forPath(nodePath + "/abc"); // System.out.println(statExist); // watcher 事件 当使用usingWatcher的时候,监听只会触发一次,监听完毕后就销毁 // cto.client.getData().usingWatcher(new MyCuratorWatcher()).forPath(nodePath); // cto.client.getData().usingWatcher(new MyWatcher()).forPath(nodePath); // 为节点添加watcher // NodeCache: 监听数据节点的变更,会触发事件 // final NodeCache nodeCache = new NodeCache(cto.client, nodePath); // // buildInitial : 初始化的时候获取node的值并且缓存 // nodeCache.start(true); // if (nodeCache.getCurrentData() != null) { // System.out.println("节点初始化数据为:" + new String(nodeCache.getCurrentData().getData())); // } else { // System.out.println("节点初始化数据为空..."); // } // nodeCache.getListenable().addListener(new NodeCacheListener() { // public void nodeChanged() throws Exception { // if (nodeCache.getCurrentData() == null) { // System.out.println("空"); // return; // } // String data = new String(nodeCache.getCurrentData().getData()); // System.out.println("节点路径:" + nodeCache.getCurrentData().getPath() + "数据:" + data); // } // }); // 为子节点添加watcher // PathChildrenCache: 监听数据节点的增删改,会触发事件 // String childNodePathCache = nodePath; // // cacheData: 设置缓存节点的数据状态 // final PathChildrenCache childrenCache = new PathChildrenCache(cto.client, childNodePathCache, true); // /** // * StartMode: 初始化方式 // * POST_INITIALIZED_EVENT:异步初始化,初始化之后会触发事件 // * NORMAL:异步初始化 // * BUILD_INITIAL_CACHE:同步初始化 // */ // childrenCache.start(StartMode.POST_INITIALIZED_EVENT); // // List<ChildData> childDataList = childrenCache.getCurrentData(); // System.out.println("当前数据节点的子节点数据列表:"); // for (ChildData cd : childDataList) { // String childData = new String(cd.getData()); // System.out.println(childData); // } // // childrenCache.getListenable().addListener(new PathChildrenCacheListener() { // public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { // if(event.getType().equals(PathChildrenCacheEvent.Type.INITIALIZED)){ // System.out.println("子节点初始化ok..."); // } // // else if(event.getType().equals(PathChildrenCacheEvent.Type.CHILD_ADDED)){ // String path = event.getData().getPath(); // if (path.equals(ADD_PATH)) { // System.out.println("添加子节点:" + event.getData().getPath()); // System.out.println("子节点数据:" + new String(event.getData().getData())); // } else if (path.equals("/super/imooc/e")) { // System.out.println("添加不正确..."); // } // // }else if(event.getType().equals(PathChildrenCacheEvent.Type.CHILD_REMOVED)){ // System.out.println("删除子节点:" + event.getData().getPath()); // }else if(event.getType().equals(PathChildrenCacheEvent.Type.CHILD_UPDATED)){ // System.out.println("修改子节点路径:" + event.getData().getPath()); // System.out.println("修改子节点数据:" + new String(event.getData().getData())); // } // } // }); Thread.sleep(3000); cto.closeZKClient(); boolean isZkCuratorStarted2 = cto.client.isStarted(); System.out.println("当前客户的状态:" + (isZkCuratorStarted2 ? "连接中" : "已关闭")); } public final static String ADD_PATH = "/super/imooc/d"; }
- 打印日志
2024-04-05 15:06:42,440 [main] [org.apache.curator.utils.Compatibility.<clinit>(Compatibility.java:41)] - [INFO] Running in ZooKeeper 3.4.x compatibility mode 2024-04-05 15:06:42,458 [main] [org.apache.curator.CuratorZookeeperClient.<init>(CuratorZookeeperClient.java:120)] - [WARN] session timeout [10000] is less than connection timeout [15000] 2024-04-05 15:06:42,469 [main] [org.apache.curator.framework.imps.CuratorFrameworkImpl.start(CuratorFrameworkImpl.java:284)] - [INFO] Starting 2024-04-05 15:06:42,477 [main] [org.apache.zookeeper.Environment.logEnv(Environment.java:100)] - [INFO] Client environment:zookeeper.version=3.4.11-37e277162d567b55a07d1755f0b31c32e93c01a0, built on 11/01/2017 18:06 GMT 2024-04-05 15:06:42,477 [main] [org.apache.zookeeper.Environment.logEnv(Environment.java:100)] - [INFO] Client environment:host.name=LAPTOP-BNI9B7NU 2024-04-05 15:06:42,478 [main] [org.apache.zookeeper.Environment.logEnv(Environment.java:100)] - [INFO] Client environment:java.version=17.0.10 2024-04-05 15:06:42,478 [main] [org.apache.zookeeper.Environment.logEnv(Environment.java:100)] - [INFO] Client environment:java.vendor=Eclipse Adoptium 2024-04-05 15:06:42,478 [main] [org.apache.zookeeper.Environment.logEnv(Environment.java:100)] - [INFO] Client environment:java.home=D:\java\develop\STS\anZh\sts-4.22.0.RELEASE\plugins\org.eclipse.justj.openjdk.hotspot.jre.full.win32.x86_64_17.0.10.v20240120-1143\jre 2024-04-05 15:06:42,478 [main] [org.apache.zookeeper.Environment.logEnv(Environment.java:100)] - [INFO] Client environment:java.class.path=D:\project\xin\zk_sts_imooc\imooc-zk-curator-maven\target\classes;C:\Users\18612\.m2\repository\org\apache\curator\curator-framework\4.0.0\curator-framework-4.0.0.jar;C:\Users\18612\.m2\repository\org\apache\curator\curator-client\4.0.0\curator-client-4.0.0.jar;C:\Users\18612\.m2\repository\com\google\guava\guava\20.0\guava-20.0.jar;C:\Users\18612\.m2\repository\org\apache\curator\curator-recipes\4.0.0\curator-recipes-4.0.0.jar;C:\Users\18612\.m2\repository\org\apache\zookeeper\zookeeper\3.4.11\zookeeper-3.4.11.jar;C:\Users\18612\.m2\repository\log4j\log4j\1.2.16\log4j-1.2.16.jar;C:\Users\18612\.m2\repository\jline\jline\0.9.94\jline-0.9.94.jar;C:\Users\18612\.m2\repository\org\apache\yetus\audience-annotations\0.5.0\audience-annotations-0.5.0.jar;C:\Users\18612\.m2\repository\io\netty\netty\3.10.5.Final\netty-3.10.5.Final.jar;C:\Users\18612\.m2\repository\joda-time\joda-time\2.5\joda-time-2.5.jar;C:\Users\18612\.m2\repository\org\apache\commons\commons-lang3\3.3.2\commons-lang3-3.3.2.jar;C:\Users\18612\.m2\repository\commons-io\commons-io\1.3.2\commons-io-1.3.2.jar;C:\Users\18612\.m2\repository\commons-net\commons-net\3.3\commons-net-3.3.jar;C:\Users\18612\.m2\repository\com\fasterxml\jackson\core\jackson-databind\2.7.4\jackson-databind-2.7.4.jar;C:\Users\18612\.m2\repository\com\fasterxml\jackson\core\jackson-core\2.7.4\jackson-core-2.7.4.jar;C:\Users\18612\.m2\repository\com\fasterxml\jackson\core\jackson-annotations\2.7.4\jackson-annotations-2.7.4.jar;C:\Users\18612\.m2\repository\org\apache\httpcomponents\httpclient\4.3.5\httpclient-4.3.5.jar;C:\Users\18612\.m2\repository\org\apache\httpcomponents\httpcore\4.3.2\httpcore-4.3.2.jar;C:\Users\18612\.m2\repository\commons-logging\commons-logging\1.1.3\commons-logging-1.1.3.jar;C:\Users\18612\.m2\repository\commons-codec\commons-codec\1.6\commons-codec-1.6.jar;C:\Users\18612\.m2\repository\org\mybatis\mybatis\3.2.8\mybatis-3.2.8.jar;C:\Users\18612\.m2\repository\org\mybatis\mybatis-spring\1.2.2\mybatis-spring-1.2.2.jar;C:\Users\18612\.m2\repository\com\github\miemiedev\mybatis-paginator\1.2.15\mybatis-paginator-1.2.15.jar;C:\Users\18612\.m2\repository\com\github\pagehelper\pagehelper\4.1.3\pagehelper-4.1.3.jar;C:\Users\18612\.m2\repository\com\github\jsqlparser\jsqlparser\0.9.4\jsqlparser-0.9.4.jar;C:\Users\18612\.m2\repository\mysql\mysql-connector-java\5.1.41\mysql-connector-java-5.1.41.jar;C:\Users\18612\.m2\repository\com\alibaba\druid\1.1.0\druid-1.1.0.jar;C:\Users\18612\.m2\repository\org\springframework\spring-core\4.3.3.RELEASE\spring-core-4.3.3.RELEASE.jar;C:\Users\18612\.m2\repository\org\springframework\spring-context\4.3.3.RELEASE\spring-context-4.3.3.RELEASE.jar;C:\Users\18612\.m2\repository\org\springframework\spring-aop\4.3.3.RELEASE\spring-aop-4.3.3.RELEASE.jar;C:\Users\18612\.m2\repository\org\springframework\spring-expression\4.3.3.RELEASE\spring-expression-4.3.3.RELEASE.jar;C:\Users\18612\.m2\repository\org\springframework\spring-context-support\4.3.3.RELEASE\spring-context-support-4.3.3.RELEASE.jar;C:\Users\18612\.m2\repository\org\springframework\spring-beans\4.3.3.RELEASE\spring-beans-4.3.3.RELEASE.jar;C:\Users\18612\.m2\repository\org\springframework\spring-webmvc\4.3.3.RELEASE\spring-webmvc-4.3.3.RELEASE.jar;C:\Users\18612\.m2\repository\org\springframework\spring-web\4.3.3.RELEASE\spring-web-4.3.3.RELEASE.jar;C:\Users\18612\.m2\repository\org\springframework\spring-jdbc\4.3.3.RELEASE\spring-jdbc-4.3.3.RELEASE.jar;C:\Users\18612\.m2\repository\org\springframework\spring-tx\4.3.3.RELEASE\spring-tx-4.3.3.RELEASE.jar;C:\Users\18612\.m2\repository\org\springframework\spring-aspects\4.3.3.RELEASE\spring-aspects-4.3.3.RELEASE.jar;C:\Users\18612\.m2\repository\org\aspectj\aspectjweaver\1.8.9\aspectjweaver-1.8.9.jar;C:\Users\18612\.m2\repository\jstl\jstl\1.2\jstl-1.2.jar;C:\Users\18612\.m2\repository\javax\servlet\servlet-api\2.5\servlet-api-2.5.jar;C:\Users\18612\.m2\repository\javax\servlet\jsp-api\2.0\jsp-api-2.0.jar;C:\Users\18612\.m2\repository\commons-fileupload\commons-fileupload\1.3.1\commons-fileupload-1.3.1.jar;C:\Users\18612\.m2\repository\redis\clients\jedis\2.8.0\jedis-2.8.0.jar;C:\Users\18612\.m2\repository\org\apache\commons\commons-pool2\2.3\commons-pool2-2.3.jar;C:\Users\18612\.m2\repository\org\apache\solr\solr-solrj\4.10.3\solr-solrj-4.10.3.jar;C:\Users\18612\.m2\repository\org\apache\httpcomponents\httpmime\4.3.1\httpmime-4.3.1.jar;C:\Users\18612\.m2\repository\org\codehaus\woodstox\wstx-asl\3.2.7\wstx-asl-3.2.7.jar;C:\Users\18612\.m2\repository\org\noggit\noggit\0.5\noggit-0.5.jar;C:\Users\18612\.m2\repository\commons-httpclient\commons-httpclient\3.1\commons-httpclient-3.1.jar;C:\Users\18612\.m2\repository\org\slf4j\slf4j-api\1.7.21\slf4j-api-1.7.21.jar;C:\Users\18612\.m2\repository\org\slf4j\slf4j-log4j12\1.7.21\slf4j-log4j12-1.7.21.jar 2024-04-05 15:06:42,478 [main] [org.apache.zookeeper.Environment.logEnv(Environment.java:100)] - [INFO] Client environment:java.library.path=D:\java\develop\STS\anZh\sts-4.22.0.RELEASE\plugins\org.eclipse.justj.openjdk.hotspot.jre.full.win32.x86_64_17.0.10.v20240120-1143\jre\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;D:/java/develop/STS/anZh/sts-4.22.0.RELEASE//plugins/org.eclipse.justj.openjdk.hotspot.jre.full.win32.x86_64_17.0.10.v20240120-1143/jre/bin/server;D:/java/develop/STS/anZh/sts-4.22.0.RELEASE//plugins/org.eclipse.justj.openjdk.hotspot.jre.full.win32.x86_64_17.0.10.v20240120-1143/jre/bin;D:\java\transport\secureCRT\anZh\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR;C:\Program Files\Git\cmd;C:\Users\18612\.dnx\bin;C:\Program Files\Microsoft DNX\Dnvm\;C:\Program Files\Microsoft SQL Server\120\Tools\Binn\;C:\Program Files (x86)\nodejs\;C:\Program Files (x86)\Windows Kits\10\Windows Performance Toolkit\;C:\Program Files (x86)\QuickTime\QTSystem\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\MySQL\MySQL Shell 8.0\bin\;C:\Users\18612\AppData\Local\Programs\Python\Python35\Scripts\;C:\Users\18612\AppData\Local\Programs\Python\Python35\;C:\Users\18612\AppData\Local\Microsoft\WindowsApps;D:\java\envir\jdk1.8\anZh\bin;D:\java\envir\jdk1.8\anZh\jre\bin;D:\Python\Fiddle\anZh;C:\Users\18612\AppData\Roaming\npm;C:\Program Files (x86)\Windows Kits\10\Include\10.0.22000.0\ucrt;C:\Program Files (x86)\Tencent\QQGameTempest\Hall.57795\;C:\Users\18612\AppData\Local\Microsoft\WindowsApps;D:\java\maven\apache-maven-3.8.2\bin;;D:\java\develop\STS\anZh\sts-4.22.0.RELEASE;;. 2024-04-05 15:06:42,479 [main] [org.apache.zookeeper.Environment.logEnv(Environment.java:100)] - [INFO] Client environment:java.io.tmpdir=C:\Users\18612\AppData\Local\Temp\ 2024-04-05 15:06:42,479 [main] [org.apache.zookeeper.Environment.logEnv(Environment.java:100)] - [INFO] Client environment:java.compiler=<NA> 2024-04-05 15:06:42,479 [main] [org.apache.zookeeper.Environment.logEnv(Environment.java:100)] - [INFO] Client environment:os.name=Windows 11 2024-04-05 15:06:42,479 [main] [org.apache.zookeeper.Environment.logEnv(Environment.java:100)] - [INFO] Client environment:os.arch=amd64 2024-04-05 15:06:42,479 [main] [org.apache.zookeeper.Environment.logEnv(Environment.java:100)] - [INFO] Client environment:os.version=10.0 2024-04-05 15:06:42,479 [main] [org.apache.zookeeper.Environment.logEnv(Environment.java:100)] - [INFO] Client environment:user.name=18612 2024-04-05 15:06:42,481 [main] [org.apache.zookeeper.Environment.logEnv(Environment.java:100)] - [INFO] Client environment:user.home=C:\Users\18612 2024-04-05 15:06:42,482 [main] [org.apache.zookeeper.Environment.logEnv(Environment.java:100)] - [INFO] Client environment:user.dir=D:\project\xin\zk_sts_imooc\imooc-zk-curator-maven 2024-04-05 15:06:42,482 [main] [org.apache.zookeeper.ZooKeeper.<init>(ZooKeeper.java:441)] - [INFO] Initiating client connection, connectString=172.26.139.4:2181 sessionTimeout=10000 watcher=org.apache.curator.ConnectionState@5158b42f 2024-04-05 15:06:42,604 [main-SendThread(172.26.139.4:2181)] [org.apache.zookeeper.ClientCnxn$SendThread.logStartConnect(ClientCnxn.java:1035)] - [INFO] Opening socket connection to server 172.26.139.4/172.26.139.4:2181. Will not attempt to authenticate using SASL (unknown error) 2024-04-05 15:06:42,604 [main] [org.apache.curator.framework.imps.CuratorFrameworkImpl.start(CuratorFrameworkImpl.java:326)] - [INFO] Default schema 当前客户的状态:连接中 2024-04-05 15:06:42,608 [main-SendThread(172.26.139.4:2181)] [org.apache.zookeeper.ClientCnxn$SendThread.primeConnection(ClientCnxn.java:877)] - [INFO] Socket connection established to 172.26.139.4/172.26.139.4:2181, initiating session 2024-04-05 15:06:42,615 [main-SendThread(172.26.139.4:2181)] [org.apache.zookeeper.ClientCnxn$SendThread.onConnected(ClientCnxn.java:1302)] - [INFO] Session establishment complete on server 172.26.139.4/172.26.139.4:2181, sessionid = 0x10016d7df88001b, negotiated timeout = 10000 2024-04-05 15:06:42,620 [main-EventThread] [org.apache.curator.framework.state.ConnectionStateManager.postState(ConnectionStateManager.java:237)] - [INFO] State change: CONNECTED 2024-04-05 15:06:42,640 [main] [org.apache.curator.utils.ZKPaths$CreateModeHolder.<clinit>(ZKPaths.java:76)] - [WARN] The version of ZooKeeper being used doesn't support Container nodes. CreateMode.PERSISTENT will be used instead. 2024-04-05 15:06:45,666 [Curator-Framework-0] [org.apache.curator.framework.imps.CuratorFrameworkImpl.backgroundOperationsLoop(CuratorFrameworkImpl.java:924)] - [INFO] backgroundOperationsLoop exiting 2024-04-05 15:06:45,670 [main] [org.apache.zookeeper.ZooKeeper.close(ZooKeeper.java:687)] - [INFO] Session: 0x10016d7df88001b closed 当前客户的状态:已关闭
- linux客户端查看是否创建节点
--linux客户端连接服务端 ./zkCli.sh --查看工作空间是否创建 [zk: localhost:2181(CONNECTED) 5] ls / [imooc-fake, workspace, imooc2, names, zookeeper, imooc3, aclimooc, imooc, testnode, imooc5] --查看节点是否创建 [zk: localhost:2181(CONNECTED) 6] ls /workspace/super/imooc [] --查看节点信息 [zk: localhost:2181(CONNECTED) 7] get /workspace/super/imooc superme cZxid = 0xc3 ctime = Fri Apr 05 15:06:42 CST 2024 mZxid = 0xc3 mtime = Fri Apr 05 15:06:42 CST 2024 pZxid = 0xc3 cversion = 0 dataVersion = 0 aclVersion = 0 ephemeralOwner = 0x0 dataLength = 7 numChildren = 0
诸葛