ZooKeeper 基本操作 与 Java APIs

前言

在前章ZooKeeper安装(集群化)我们安装ZooKeeper集群. 本章, 我们讲解下ZooKeeper的基本操作.


命令行操作

我们通常使用zkCli.sh脚本进行登陆.登陆命令:./zkCli.sh --server 192.168.31.60:2181
其后,基本操作主要有如下几种:

  • help命令
    显示客户所支持的所有命令,如:
[zk: 192.168.31.60:2181(CONNECTED) 2] h
ZooKeeper -server host:port cmd args
	stat path [watch]
	set path data [version]
	ls path [watch]
	delquota [-n|-b] path
	ls2 path [watch]
	setAcl path acl
	setquota -n|-b val path
	history
	redo cmdno
	printwatches on|off
	delete path [version]
	sync path
	listquota path
	rmr path
	get path [watch]
	create [-s] [-e] path data acl
	addauth scheme auth
	quit
	getAcl path
	close
	connect host:port

其中, 用的比较多的有create/ls/delete/set/close/rmr.

  • create [-s] [-e] path data acl -s为顺序充点,-e临时节点
    例如:create /servers/hello/1 "123" world:anyone:cdrwa 需要特别注意的是,创建的父结点需要存在.否则会创建失败.
# 失败
[zk: 192.168.31.60:2181(CONNECTED) 7] create /servers/hello/1 ""
Node does not exist: /servers/hello/1
# 成功
[zk: 192.168.31.60:2181(CONNECTED) 13] create /servers/hello "123" world:anyone:cdrwa
Created /servers/hello
  • ls path [watch] 其中[watch]相当于观察者.回调函数.
[zk: 192.168.31.60:2181(CONNECTED) 17] ls /servers
[hello]
  • delete path [version] 删除单个结点.注意不能循环删除.(即/servers/hello无法直接删除父亲结点/servers,需要先删除子结点再删除父结点. )
# 删除失败
[zk: 192.168.31.60:2181(CONNECTED) 15] delete /servers
Node not empty: /servers
# 删除成功
[zk: 192.168.31.60:2181(CONNECTED) 19] delete /servers/hello/1
[zk: 192.168.31.60:2181(CONNECTED) 20] delete /servers/hello
[zk: 192.168.31.60:2181(CONNECTED) 22] delete /servers
  • set path data [version]get path [watch]: 设置结点 / 获得结点
[zk: 192.168.31.60:2181(CONNECTED) 25] get /servers
"123"
cZxid = 0x30000000d
ctime = Sat Mar 23 06:26:54 PDT 2019
mZxid = 0x30000000d
mtime = Sat Mar 23 06:26:54 PDT 2019
pZxid = 0x30000000d
cversion = 0
dataVersion = 0
aclVersion = 0
ephemeralOwner = 0x0
dataLength = 5
numChildren = 0
[zk: 192.168.31.60:2181(CONNECTED) 26] set /servers "456"
cZxid = 0x30000000d
ctime = Sat Mar 23 06:26:54 PDT 2019
mZxid = 0x30000000e
mtime = Sat Mar 23 06:27:19 PDT 2019
pZxid = 0x30000000d
cversion = 0
dataVersion = 1
aclVersion = 0
ephemeralOwner = 0x0
dataLength = 5
numChildren = 0
[zk: 192.168.31.60:2181(CONNECTED) 27] get /servers
"456"
cZxid = 0x30000000d
ctime = Sat Mar 23 06:26:54 PDT 2019
mZxid = 0x30000000e
mtime = Sat Mar 23 06:27:19 PDT 2019
pZxid = 0x30000000d
cversion = 0
dataVersion = 1
aclVersion = 0
ephemeralOwner = 0x0
dataLength = 5
numChildren = 0
  • rmr path 强制删除.可以级联删除.
[zk: 192.168.31.60:2181(CONNECTED) 29] rmr /servers
  • history查看历史命令
[zk: 192.168.31.60:2181(CONNECTED) 30] history
20 - delete /servers/hello
21 - delete /servers/
22 - delete /servers
23 - ls
24 - create /servers "123"
25 - get /servers
26 - set /servers "456"
27 - get /servers
28 - rmr servers
29 - rmr /servers
30 - history
  • stat查看结点信息
[zk: 192.168.31.60:2181(CONNECTED) 32] stat /servers
cZxid = 0x300000010
ctime = Sat Mar 23 06:29:53 PDT 2019
mZxid = 0x300000010
mtime = Sat Mar 23 06:29:53 PDT 2019
pZxid = 0x300000010
cversion = 0
dataVersion = 0
aclVersion = 0
ephemeralOwner = 0x0
dataLength = 5
numChildren = 0
  • close: 断开客户端与服务端的连接.
  • ls2: ls的扩展,多显示一层.
  • setquota 设置子结点配额.
# 设置/zookeeper/node子节点个数最大为4
[zk: 192.168.31.60:2181(CONNECTED) 39] setquota -n 4   /servers
Comment: the parts are option -n val 4 path /servers
# 设置/zookeeper/node节点长度最大为100
setquota –b 100 /zookeeper/node 
[zk: 192.168.31.60:2181(CONNECTED) 40] setquota -b 100   /servers
Comment: the parts are option -b val 100 path /servers
Command failed: java.lang.IllegalArgumentException: /servers has a parent /zookeeper/quota/servers which has a quota
# 貌似只能选择其一
  • delquota 删除配额. -n为子节点个数, -b为节点数据长度.如delquota –n 2.
  • listquota 显示配额.没有配置则显示为空.
# 不显示
[zk: 192.168.31.60:2181(CONNECTED) 41] listquota /servers/hello
absolute path is /zookeeper/quota/servers/hello/zookeeper_limits
quota for /servers/hello does not exist.
# 显示
[zk: 192.168.31.60:2181(CONNECTED) 42] listquota /servers
absolute path is /zookeeper/quota/servers/zookeeper_limits
Output quota for /servers count=4,bytes=-1
Output stat for /servers count=2,bytes=18
  • printwatches: 设置和显示监视状态, on或者off. printwatches on

  • sync: 强制同步. 如sync /servers. 由于请求在半数以上的zk server上生效就表示此请求生效, 那么就会有一些zk server上的数据是旧的. sync命令就是强制同步所有的更新操作.(即所有的都更新完毕后,再进行其他操作.)

  • redo: 再次执行某命令. 如redo 10. 其中10为命令ID,需与history配合使用。

setAcl命令: 设置节点Acl.

此处重点说一下acl,acl由大部分组成:1为scheme,2为user,3为permission,一般情况下表示为scheme?permissions。

其中scheme和id是相关的,下面将scheme和id一起说明。

  • scheme和id
    world: 它下面只有一个id, 叫anyone, world:anyone代表任何人,zookeeper中对>所有人有权限的结点就是属于world:anyone的.
  • auth: 它不需要id, 只要是通过authentication的user都有权限(zookeeper支持通过kerberos来进行authencation, 也支持username/password形式的authentication)
  • digest: 它对应的id为username:BASE64(SHA1(password)),它需要先通过username:password形式的authentication
  • ip: 它对应的id为客户机的IP地址,设置的时候可以设置一个ip段,比如ip:192.168.1.0/16, 表示匹配前16个bit的IP段
    super: 在这种scheme情况下,对应的id拥有超级权限,可以做任何事情(cdrwa)
  • permissions
    CREATE©: 创建权限,可以在在当前node下创建child node
    DELETE(d): 删除权限,可以删除当前的node
    READ®: 读权限,可以获取当前node的数据,可以list当前node所有的child nodes
    WRITE(w): 写权限,可以向当前node写数据
    ADMIN(a): 管理权限,可以设置当前node的permission
    综上,一个简单使用setAcl命令,则可以为:
    setAcl /zookeeper/node1 world:anyone:cdrw
  • getAcl: 获取节点Acl。如
getAcl /zookeeper/node1
'world,'anyone
: cdrwa

注:可参见setAcl命令。

addauth: 节点认证。
addauth digest username:password,可参见setAcl命令digest处。
使用方法:
一、通过setAcl设置用户名和密码

setAcl pathdigest:username:base64(sha1(password)):crwda

二、认证

addauth digest username:password


Java API

ZooKeeper提供的API主要使用的有:

  • ZooKeeper

  • ZKClient

  • Cursor
    三种包的使用有点不太相同.但是都是基于命令行的形式,完成了它们各自的API. 主要提供都API:皆为zkClient()/create()/delete()/exists()/getChildren()等等.

  • ZooKeeper

 	<!-- ZK Dependence -->
  	<dependency>
      <groupId>org.apache.zookeeper</groupId>
      <artifactId>zookeeper</artifactId>
      <version>3.4.6</version>
    </dependency> 

OriginZooKeeperAPIs

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.List;

public class OriginZooKeeperAPIs {

    private static String connStr =  "192.168.31.60:2181,192.168.31.61:2181,192.168.31.62:2181";
    private static int timeout = 2000;

    private static ZooKeeper zooKeeper =  null;

    //建立客户端连接
    public static void init() throws IOException {
        zooKeeper = new ZooKeeper(connStr, timeout, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                System.out.println(watchedEvent.getType()+"  ---  " + watchedEvent.getPath());
                try {
                    zooKeeper.getChildren("/",true);
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
        init();
//        createNode();
//        exist();
//        getChildren();
//        deleteNode();
//        exist();
        getData();
    }

    //创建节点
    public static void createNode() throws KeeperException, InterruptedException {
        String s = zooKeeper.create("/sean", "zs".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        System.out.println(s);
    }

    //判断节点是否存在
    public static void exist() throws KeeperException, InterruptedException {
        Stat stat = zooKeeper.exists("/sean", false);
        System.out.println(stat==null?"not exist":"exist");
    }

    //获取子节点
    public static void getChildren() throws KeeperException, InterruptedException {
        List<String> children = zooKeeper.getChildren("/", true);
        children.stream().forEach(
                child -> System.out.println(child)
        );
        Thread.sleep(Long.MAX_VALUE);
    }
    //删除
    public static void deleteNode() throws KeeperException, InterruptedException {
        zooKeeper.delete("/sean",-1);
    }

    //获取节点数据
    public static void getData() throws KeeperException, InterruptedException {
        byte[] data = zooKeeper.getData("/sean", true, null);
        System.out.println(new String(data));
    }

    //更改节点数据
    public static void setData() throws KeeperException, InterruptedException {
        zooKeeper.setData("/sean","sean".getBytes(),2);
    }


}
  • ZKClient
  	<!-- ZK Dependence -->
  	<dependency>
      <groupId>org.apache.zookeeper</groupId>
      <artifactId>zookeeper</artifactId>
      <version>3.4.6</version>
    </dependency>    
    <dependency>
      <groupId>com.101tec</groupId>
      <artifactId>zkclient</artifactId>
      <version>0.5</version>
    </dependency>

OriginalClientAPIs

package com.yanxml.zookeeper.original.zkclient;

import java.util.List;

import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.serialize.SerializableSerializer;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

import com.yanxml.zookeeper.business.User;
import com.yanxml.zookeeper.config.ZooKeeperConfig;

public class OriginalClientAPIs {

	// 获取ZooKeeper客户端
	public ZkClient getClient() {
		ZkClient zkClient = null;
		zkClient = new ZkClient(ZooKeeperConfig.ZOOURLS, 10000, 10000,
				new SerializableSerializer());
		return zkClient;
	}

	// 创建一个节点&创建节点的子节点
	public String createZkNode(ZkClient zkClient) {
		String path = "";
		if (null != zkClient) {
			if (!zkClient.exists("/user")) {
				User user = new User("Sean", 24);
				path = zkClient.create("/user", user, CreateMode.PERSISTENT);
				// log.warn
			}
			// 创建子节点
			if (!zkClient.exists("/user/petter")) {
				User user = new User("Petter", 24);
				path = zkClient.create("/user/petter", user,
						CreateMode.PERSISTENT);
			}
			// 创建子节点
			if (!zkClient.exists("/user/bruce")) {
				User user = new User("Bruce", 24);
				path = zkClient.create("/user/bruce", user,
						CreateMode.PERSISTENT);
			}
			// 创建子子节点
			if (!zkClient.exists("/user/bruce/abel")) {
				User user = new User("Abel", 24);
				path = zkClient.create("/user/bruce/abel", user,
						CreateMode.PERSISTENT);
			}
		}
		return path;
	}

	// 获取一个节点
	public Object getZkNode(ZkClient zkClient) {
		User user = null;
		if (null != zkClient) {
			Stat stat = new Stat();
			user = zkClient.readData("/user", stat);
			System.out.println(
					"user:" + user.toString() + " stat:" + stat.toString());
			return user;
		}
		return user;
	}

	// 获取子节点(只向下获取一层 儿子的儿子节点不会获取)
	public List<String> getChildZkNode(ZkClient zkClient) {
		List<String> resultObj = null;
		if (null != zkClient) {
			resultObj = zkClient.getChildren("/user");
			System.out.println("Children String List: " + resultObj);
		}
		return resultObj;

	}

	// 查询节点是否存在
	public boolean existZkNode(ZkClient zkClient) {
		boolean flag = false;
		if (null != zkClient) {
			flag = zkClient.exists("/user");
			System.out.println("Node Exists: " + " '/user' " + flag);
		}
		return flag;
	}

	// 删除&循环删除
	public boolean deleteZkNode(ZkClient zkClient) {
		boolean flag = false;
		if (null != zkClient) {
			// 单节点删除(当存在子节点时候 会出现删除失败的情况)
			// flag = zkClient.delete("/user");

			// System.out.println("Delete OK " + " '/user' " + flag);

			// 循环删除
			flag = zkClient.deleteRecursive("/user");
			System.out.println("Recursive delete OK " + " '/user' " + flag);

		}
		return flag;
	}

	// 修改节点内容
	public boolean updateZkNode(ZkClient zkClient){
		boolean flag = false;
		if( null != zkClient){
			if(zkClient.exists("/user")){
				User user = new User("ChiGua", 24);
				zkClient.writeData("/user", user);
			}
		}
		return flag;
	}

	public static void main(String[] args) {
		OriginalClientAPIs apisDemo = new OriginalClientAPIs();

		// 获取client端
		ZkClient zkClient = apisDemo.getClient();
		// 创建节点
		apisDemo.createZkNode(zkClient);
		// 获取节点
		apisDemo.getZkNode(zkClient);

		// 获取从节点 地址
		apisDemo.getChildZkNode(zkClient);

		// apisDemo.existZkNode(zkClient);

		// apisDemo.deleteZkNode(zkClient);
		
		apisDemo.updateZkNode(zkClient);


	}

}

// Bug1:创建 原节点已经存在 创建失败

// Bug2:节点包含子节点 删除失败
// Exception in thread "main" org.I0Itec.zkclient.exception.ZkException:
// org.apache.zookeeper.KeeperException$NotEmptyException: KeeperErrorCode =
// Directory not empty for /user
// at org.I0Itec.zkclient.exception.ZkException.create(ZkException.java:68)
// at org.I0Itec.zkclient.ZkClient.retryUntilConnected(ZkClient.java:893)
// at org.I0Itec.zkclient.ZkClient.delete(ZkClient.java:936)
// at
// com.yanxml.zookeeper.original.zkclient.OriginalClientAPIs.deleteZkNode(OriginalClientAPIs.java:84)
// at
// com.yanxml.zookeeper.original.zkclient.OriginalClientAPIs.main(OriginalClientAPIs.java:112)
// Caused by: org.apache.zookeeper.KeeperException$NotEmptyException:
// KeeperErrorCode = Directory not empty for /user
// at org.apache.zookeeper.KeeperException.create(KeeperException.java:125)
// at org.apache.zookeeper.KeeperException.create(KeeperException.java:51)
// at org.apache.zookeeper.ZooKeeper.delete(ZooKeeper.java:873)
// at org.I0Itec.zkclient.ZkConnection.delete(ZkConnection.java:102)
// at org.I0Itec.zkclient.ZkClient$9.call(ZkClient.java:940)
// at org.I0Itec.zkclient.ZkClient.retryUntilConnected(ZkClient.java:883)
// ... 3 more

SubscribeChildChanges.java

package com.yanxml.zookeeper.original.zkclient;

import java.util.List;
import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.ZkClient;

public class SubscribeChildChanges {
	
	
	private static class ZkChildListener implements IZkChildListener{

		public void handleChildChange(String parentPath, List<String> currentChilds)
				throws Exception {
			System.out.println(parentPath);
			System.out.println(currentChilds.toString());
		}
		
	}
	
	public static void main(String[] args) throws InterruptedException {
		OriginalClientAPIs apisDemo = new OriginalClientAPIs();
		// 获取client端
		ZkClient zkClient = apisDemo.getClient();
		
		// 注意 这个方法只能往下监听一层 子子节点的改变不能获取到
		zkClient.subscribeChildChanges("/user", new ZkChildListener());
		Thread.sleep(Integer.MAX_VALUE);
	}

}

SubscribeDataChanges.java

package com.yanxml.zookeeper.original.zkclient;

import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;


public class SubscribeDataChanges {
	
	private static class ZkDataListener implements IZkDataListener{

		public void handleDataChange(String dataPath, Object data)
				throws Exception {
			System.out.println(dataPath+":"+data.toString());
		}

		public void handleDataDeleted(String dataPath) throws Exception {
			System.out.println("Deleted:"+dataPath);
		}
		
	}
	
	public static void main(String[] args) throws InterruptedException {
		OriginalClientAPIs apisDemo = new OriginalClientAPIs();
		// 获取client端
		ZkClient zkClient = apisDemo.getClient();
		
		// 注意 这个方法只能往下监听一层 子子节点的改变不能获取到
		zkClient.subscribeDataChanges("/user", new ZkDataListener());
		Thread.sleep(Integer.MAX_VALUE);
		
		// 监听相关的方法
//		zkClient.unsubscribeAll();
//		zkClient.unsubscribeChildChanges(arg0, arg1);
//		zkClient.unsubscribeDataChanges(arg0, arg1);
//		zkClient.unsubscribeStateChanges(stateListener);
		
	}

}

  • Curator
   <!-- cursor  -->
    <dependency>
        <groupId>org.apache.curator</groupId>
        <artifactId>curator-recipes</artifactId>
        <version>2.8.0</version>
    </dependency>
    
    <!-- fast json -->
    <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
	<dependency>
    	<groupId>com.alibaba</groupId>
    	<artifactId>fastjson</artifactId>
    	<version>1.2.28</version>
	</dependency>
    

CuratorAPIs

package com.yanxml.zookeeper.original.curator;

import java.security.NoSuchAlgorithmException;
import java.security.acl.Acl;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.BackgroundCallback;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.retry.RetryUntilElapsed;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs.Perms;
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 com.yanxml.zookeeper.config.ZooKeeperConfig;

// curator 馆长

public class CuratorAPIs {

	// Get The ZkClient
	public static CuratorFramework getClient() {
		CuratorFramework zkClient = null;
		// RetryPolicy 重试策略 Elapsed 运行
		// RetryUntilElapsed(maxElapsedTimeMs, sleepMsBetweenRetries)
		RetryPolicy retryPolicy = new RetryUntilElapsed(5000, 1000);

		// create method 1:
		// zkClient = CuratorFrameworkFactory.newClient(ZooKeeperConfig.ZOOURLS,
		// retryPolicy);

		// create method 2:
		zkClient = CuratorFrameworkFactory.builder()
				.connectString(ZooKeeperConfig.ZOOURLS)
				.connectionTimeoutMs(5000).sessionTimeoutMs(5000)
				.retryPolicy(retryPolicy).build();

		zkClient.start();

		return zkClient;
	}

	// create the zk node
	public boolean createZkNode(CuratorFramework curatorFramework)
			throws Exception {
		boolean flag = false;
		if (null != curatorFramework) {
			// 如何将一个对象转换为二进制流
			// EPHEMERAL短暂的
			String path = curatorFramework.create().creatingParentsIfNeeded()
					.withMode(CreateMode.EPHEMERAL)
					.forPath("/user/sean", "123".getBytes());
			System.out.println("Create Path: " + path);
			flag = true;
		}
		return flag;
	}

	// delete the zk node
	public boolean deleteZkNode(CuratorFramework curatorFramework)
			throws Exception {
		boolean flag = false;
		if (null != curatorFramework) {
			curatorFramework.delete().deletingChildrenIfNeeded().withVersion(-1)
					.forPath("/user/sean");
			flag = true;
		}
		return flag;
	}

	// get the zk node
	public boolean getZkNode(CuratorFramework curatorFramework)
			throws Exception {
		boolean flag = false;
		if (null != curatorFramework) {
			Stat stat = new Stat();
			byte result[] = curatorFramework.getData().storingStatIn(stat)
					.forPath("/user/sean");
			System.out.println(new String(result));
			flag = true;
		}
		return flag;
	}

	// get the child zk node
	public boolean getChildZkNode(CuratorFramework curatorFramework)
			throws Exception {
		boolean flag = false;
		if (null != curatorFramework) {
			List<String> resultList = curatorFramework.getChildren()
					.forPath("/user");
			System.out.println(resultList.toString());
			flag = true;
		}
		return flag;
	}

	// change the child zk node
	public boolean changeZkNode(CuratorFramework curatorFramework)
			throws Exception {
		boolean flag = false;
		if (null != curatorFramework) {
			Stat stat = new Stat();
			curatorFramework.getData().storingStatIn(stat)
					.forPath("/user/sean");
			curatorFramework.setData().withVersion(stat.getVersion())
					.forPath("/user/sean", "456".getBytes());
			flag = true;
		}
		return flag;
	}

	// check the child zk node
	public boolean checkZkNode(CuratorFramework curatorFramework)
			throws Exception {
		boolean flag = false;

		ExecutorService es = Executors.newFixedThreadPool(5);

		if (null != curatorFramework) {
			// 获取节点的状态值
			Stat stat = curatorFramework.checkExists().forPath("/user/sean");
			System.out.println(stat.toString());

			curatorFramework.checkExists()
					.inBackground(new BackgroundCallback() {

						public void processResult(CuratorFramework arg0,
								CuratorEvent arg1) throws Exception {
							Stat stat = arg1.getStat();
							System.out.println(stat);
							// arg1.getContext() 即为"123" 存储在ZkNode内的String 字符串
							System.out.println(arg1.getContext());
						}
					}, "123", es).forPath("/user/sean");
			flag = true;
		}
		return flag;
	}

	// Subscribe Node & child Node
	public static boolean subscribeZkNode(CuratorFramework curatorFramework)
			throws Exception {
		boolean flag = false;
		if (null != curatorFramework) {
			flag = true;
			// NodeCache The cache value&stat of zk
			final NodeCache nodeCache = new NodeCache(curatorFramework,
					"/user/sean");
			nodeCache.start();
			nodeCache.getListenable().addListener(new NodeCacheListener() {

				public void nodeChanged() throws Exception {
					byte currentData[] = nodeCache.getCurrentData().getData();
					System.out
							.println("CurrentData:" + new String(currentData));
				}
			});
		}
		return flag;
	}

	// Subscribe Node & child Node
	public static boolean subscribeChildZkNode(
			CuratorFramework curatorFramework) throws Exception {
		boolean flag = false;
		if (null != curatorFramework) {
			flag = true;
			// NodeCache The cache value&stat of zk
			final PathChildrenCache childNodeCache = new PathChildrenCache(
					curatorFramework, "/user/sean", true);
			childNodeCache.start();

			childNodeCache.getListenable()
					.addListener(new PathChildrenCacheListener() {

						public void childEvent(CuratorFramework zkClient,
								PathChildrenCacheEvent event) throws Exception {
							// TODO Auto-generated method stub
							switch (event.getType()) {
								case CHILD_ADDED : {
									System.out.println("Add Child Node");
									break;
								}
								case CHILD_UPDATED : {
									System.out.println("Update Child Node");
									break;
								}
								case CHILD_REMOVED : {
									System.out.println("Remove Child Node");
									break;
								}
								default : {
									System.out.println("Default");
									break;
								}
							}
						}
					});
		}
		return flag;
	}

	public static boolean authorZkNode(CuratorFramework curatorFramework) throws Exception{
		boolean flag = false;
		if (null != curatorFramework) {
			ACL acl = new ACL(Perms.READ,new Id("ip","192.168.100.204"));
			// digest 所有权限都有
//			Acl aclDigest =Acl 
			ACL aclDigest = new ACL(Perms.READ|Perms.WRITE,new Id("digest",DigestAuthenticationProvider.generateDigest("jike:123456")));
			ArrayList<ACL> acls = new ArrayList<ACL>();
			acls.add(acl);
			acls.add(aclDigest);
			
			// add the acls node
			String path = curatorFramework.create()
					.creatingParentsIfNeeded()
					.withMode(CreateMode.PERSISTENT)
					.withACL(acls)
					.forPath("/jike/3","123".getBytes());
	        System.out.println(path);
			flag = true;
		}
		return flag;
	}
	
	public static void main(String[] args) throws Exception {
		CuratorAPIs curatorApIs = new CuratorAPIs();
		CuratorFramework curatorFramework = curatorApIs.getClient();

		// Create The Zk Node
		curatorApIs.createZkNode(curatorFramework);

		// Delete The Zk Node
		// curatorApIs.deleteZkNode(curatorFramework);

		// Get The Zk Node
		curatorApIs.getZkNode(curatorFramework);

		// Get The Child Zk Node
		curatorApIs.getChildZkNode(curatorFramework);

		// Change The Zk Node
		// curatorApIs.changeZkNode(curatorFramework);

		// Check The Zk Node
//		curatorApIs.checkZkNode(curatorFramework);

		curatorApIs.authorZkNode(curatorFramework);
		
		// 2^32-1
		Thread.sleep(Integer.MAX_VALUE);

	}

}


Reference

[1]. zookeeper 操作命令
[2]. zookeeper系列(一)zookeeper基础

相关推荐
©️2020 CSDN 皮肤主题: Age of Ai 设计师:meimeiellie 返回首页