直接上代码大家跟着敲一遍就明白了!
先添加Maven:
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>2.11.1</version>
</dependency>
代码如下:
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.apache.commons.lang3.StringUtils;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.transaction.CuratorTransaction;
import org.apache.curator.framework.recipes.cache.*;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.server.auth.DigestAuthenticationProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* @Author Mr.wei
* @Date 2019/12/9 16:43
* @Description:TODO
*/
public class ZKUtils {
private static Logger logger = LoggerFactory.getLogger(ZKUtils.class);
public static void main(String[] args) throws InterruptedException {
CuratorFramework client = init("192.168.8.11");
client.start();
String path = "/mytest1";
//添加权限
addAuth(client);
//创建节点
// createNode(client, path, CreateMode.PERSISTENT, "This is a node!");
// setACLForPath(client, path);
//删除节点
// deleteNode(client, path);
//删除节点及其子节点
// deletingChildrenIfNeeded(client, path);
//判断节点是否存在
// isExistNode(client,path);
//是否是持久化节点
// isPersistenNode(client, path);
//获取节点内容
// System.out.println(getNodeData(client, path));
//获取子节点
// List<String> childrenNode = getChildrenNode(client, path);
// for (String s : childrenNode) {
// System.out.println(s);
// }
//注册节点监听器
// NodeCache nodeCache = registerWatcherNodeChanged(client, path);
// System.out.println(new String(nodeCache.getCurrentData().getData()));
// Thread.sleep(5000000);
//注册子节点监听器
PathChildrenCache pathChildrenCache = registerWatcherChildrenNodeChanged(client, path);
List<ChildData> currentData = pathChildrenCache.getCurrentData();
for (ChildData currentDatum : currentData) {
System.out.println(new String(currentDatum.getData()));
}
Thread.sleep(5000000);
//更新节点内容
// updateNodeValue(client, path, "This is a new value");
//开启事务
// CuratorTransaction curatorTransaction