Curator/Zookeeper如何判断一个节点是否存在

前言

在学习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.运行结果

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值