Zookeeper学习:Zookeeper的原生java API

Zookeeper的原生java API,此处只涉及针对Zookeeper节点的操作;

一、连接Zookeeper

API里边针对连接Zookeeper有四个方法,即Zookeeper的构造方法有四种:

1、ZooKeeper(String connectString, int sessionTimeout, Watcher watcher)

2、ZooKeeper(String connectString, int sessionTimeout, Watcher watcher, boolean canBeReadOnly) 

3、ZooKeeper(String connectString, int sessionTimeout, Watcher watcher, long sessionId, byte[] sessionPasswd) 

4、ZooKeeper(String connectString, int sessionTimeout, Watcher watcher, long sessionId, byte[] sessionPasswd, boolean canBeReadOnly) 

connectString: comma separated host:port pairs, each corresponding to a zk server.

sessionTimeout: session timeout in milliseconds;

watcher:a watcher object which will be notified of state changes, may also be notified for node events;

针对第一种构造方法,这里举个栗子:

	// * Zookeeper地址
	static final String CONNECT_ADDR = "192.168.1.101:2181,192.168.1.102:2181,192.168.1.103:2181";
	// * Session超时时间
	static final int SESSION_OUTTIME = 5*1000;
    ...
	public static ZooKeeper newInstance() throws Exception{
		ZooKeeper zk = = new ZooKeeper(CONNECT_ADDR,SESSION_OUTTIME,new Watcher() {
				public void process(WatchedEvent event) {
					此处实现Watcher接口的process方法。
				}
			});
			...
		return zk;
	}

二、创建节点

关于创建节点,API里边有两个方法:

1、create(String path, byte[] data, List<ACL> acl, CreateMode createMode) //同步创建节点

2、create(String path, byte[] data, List<ACL> acl, CreateMode createMode, AsyncCallback.StringCallback cb, Object ctx) //异步创建节点

path:the path for the node (针对Zookeeper根节点的路径,以“/”开头);

data:the initial data for the node;

acl:the acl for the node(Ids:分别为

          ANYONE_ID_UNSAFE:This Id represents anyone;

          AUTH_IDS:This Id is only usable to set ACLs. It will get substituted with the Id's the client authenticated with;

          OPEN_ACL_UNSAFE:This is a completely open ACL;

          CREATOR_ALL_ACL:This ACL gives the creators authentication id's all permissions;

          READ_ACL_UNSAFE:This ACL gives the world the ability to read);

createMode:specifying whether the node to be created is ephemeral and/or sequential(此处有四种类型,分别是临时节点、临时有序节点、持久节点、持久有序节点,其中,临时节点会在session会话结束时被删除);

针对第一种方法,这里举个栗子:

String nodePath = "Node100";
result = zookeeper.create("/"+nodePath,  "凛冬将至".getBytes(), Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL);
//创建成功,打印result为:创建结果为:/Node100
//若nodePath这个节点已经存在,此次创建失败,抛出异常,打印result为:创建结果为:KeeperErrorCode = NodeExists for /Node100
//其他异常:
//KeeperException - if the server returns a non-zero error code
//KeeperException.InvalidACLException - if the ACL is invalid, null, or empty
//InterruptedException - if the transaction is interrupted
//IllegalArgumentException - if an invalid path is specified

备注:

1、Zookeeper的原生API是不能递归地去创建节点的,所以在创建节点时最好先get一下,判断有了父节点之后才创建子节点;

2、不支持java序列化,所以节点的数据都是使用:“节点数据”.getBytes();

3、权限一栏,一般选择开发权限,即acl项选择:OPEN_ACL_UNSAFE;

4、使用异步创建节点的方法时,需要注册一个异步回调函数,实现AsyncCallback接口,重写processResult方法,如:  

    	zk.create("/"+nodePath,  "凛冬将至".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, 
    			new StringCallback() {
					//异步回调函数
					public void processResult(int rc, String path, Object ctx, String name) {
						/*
						 * rc:服务端响应码,0-调用成功、-4表示端口连接、-110表示指定节点存在、-112表示会话已经过期
						 * path:调用接口时传入API的数据节点的路径参数
						 * ctx:调用接口传入API的ctx值
						 * name:实际在服务器端创建节点的名称
						 */
					}
				}, "data to StringCallback,一般为上下文信息Context");

三、删除节点

针对删除节点,API里边有两个方法:

1、void	delete(String path, int version) 

2、void	delete(String path, int version, AsyncCallback.VoidCallback cb, Object ctx) 

Path:the path of the node to be deleted;

version: the expected node version;

针对第一种方法,这里举个栗子:

String nodePath = "Node100";
int version = 0;
zookeeper.delete(“/”+nodePath, version);
//若不存在该节点,抛出异常:org.apache.zookeeper.KeeperException$NoNodeException: KeeperErrorCode = NoNode for /Node100
//若节点路径存在问题,抛出异常:java.lang.IllegalArgumentException: Path must start with / character
//其他可能的异常:InterruptedException - IF the server transaction is interrupted
//删除成功,返回值为void

四、获取节点数据

首先,获取节点路径,之后在基于父类路径上取数据(Zookeeper.getData(XXX)),此时取出的节点的数据为byte数组,可以使用new String(Zookeeper.getData())来还原显示数据。

举个栗子:

		try {
			List<String> list = zk.getChildren(nodePath, false);
			for(String node:list) {
				System.out.println(new String(zk.getData(nodePath+"/"+node, false, null)));
			}
		} catch (Exception e) {
			System.err.println(e.getMessage());
		} 
//nodepath为父节点路径

五、修改节点数据

1、Stat	setData(String path, byte[] data, int version) //同步操作

2、void	setData(String path, byte[] data, int version, AsyncCallback.StatCallback cb, Object ctx) //异步操作

举个栗子:

		//修改节点数据
		data = "我要修改节点数据".getBytes();
		try {
			//先判断指定节点是否存在
			Stat stat = zk.exists(nodePath, false);
			if(stat == null) {
				System.out.println("对应节点不存在");
			}else {
				//System.out.println(stat);
				stat = zk.setData(nodePath, data, -1);
				System.out.println("修改节点成功,返回数据stat:"+stat);
			}
		} catch (Exception e) {
			System.err.println(e.getMessage());
		} 

备注:version选择“-1”,意思即是:跳过版本检查

官方API可以到此处下载:https://download.csdn.net/download/txd2016_5_11/10906269

猜你喜欢

转载自blog.csdn.net/txd2016_5_11/article/details/86139830