前言

在学习Zookeeper时,判断节点是否存在,zk提供了一个很给力的方法,就是:

zk.exists(String nodePath, boolean ifWatch)

注:该方法非常好用,前面是node路径,后面是调用这个方法时,是否回调watch监测节点发生变化。

概述

ZK客户端Curator时,判断节点是否存在如下

1.cto.client.checkExists().forPath(nodePath);//Curator自带原生态的判断方法

2.cto.client.getZookeeperClient().getZooKeeper().exists(nodePath, false);

两种方案的本质区别:

方案一会在nodePath前自动添加workspace的前缀

方案二属于把Curator返璞归真为zk原生态,所以不会自动带workspace,需要手动添加路径的前缀workspace。 

本案例主要探讨解决方案,自己get到答案后,可自行对解决方案进行优化。

解决方案  

1.配套代码

	public CuratorFramework client = null;
	public static final String workSpace="workspace";
	public static final String zkServerPath = "192.168.31.216:2181";

	public CuratorAcl() {
		RetryPolicy retryPolicy = new RetryNTimes(3, 5000);
		client = CuratorFrameworkFactory.builder().authorization("digest", "mayun:mayun".getBytes())
				.connectString(zkServerPath)
				.sessionTimeoutMs(20000).retryPolicy(retryPolicy)
				.namespace(workSpace).build();
		client.start();
	}
	
	public void closeZKClient() {
		if (client != null) {
			this.client.close();
		}
	}

Curator有工作空间这说法,在初始化Curator客户端时,就可以登录权限,避免后面每次操作都要登录一遍。如上代码:.authorization("digest", "mayun:mayun".getBytes());就是用来自动登录的。

2.main方法核心代码(两种方法)

public static void main(String[] args) throws Exception {
		// 实例化
		CuratorAcl cto = new CuratorAcl();
		boolean isZkCuratorStarted = cto.client.isStarted();
		System.out.println("当前客户的状态:" + (isZkCuratorStarted ? "连接中" : "已关闭"));
		
		String nodePath2 = "/acl/father/child/sub";
		 
		//判断节点是否存在,方法一(路径前面会自动添加workspace)
		Stat stat=cto.client.checkExists().forPath(nodePath2);
		System.out.println("======="+stat==null?"不存在":"存在");
		
		//判断节点是否存在,方法二(路径前面需手动添加workspace)
		Stat stat2 = cto.client.getZookeeperClient().getZooKeeper().exists("/workspace"+nodePath2, false);
		System.out.println("======="+stat2==null?"不存在":"存在");
		
		
		cto.closeZKClient();
		boolean isZkCuratorStarted2 = cto.client.isStarted();
		System.out.println("当前客户的状态:" + (isZkCuratorStarted2 ? "连接中" : "已关闭"));
	}

3.运行结果

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐