Zookeeper学习笔记(二)通过Java API调用Zookeeper

一、引入依赖

<dependency>
  <groupId>org.apache.zookeeper</groupId>
  <artifactId>zookeeper</artifactId>
  <version>3.4.7</version>
</dependency>

二、常用方法简析

这里只列举了一些常用的方法,其他方法可以查看官方api:https://zookeeper.apache.org/doc/r3.4.10/api/index.html

1、Zookeeper构造方法

方法签名 参数解析
ZooKeeper(String connectString, int sessionTimeout, Watcher watcher) connectString: 连接字符串,格式为主机:端口号,多个用逗号分隔,如:127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002
sessionTimeout: session超时时间
watcher:watcher事件通知处理                                
ZooKeeper(String connectString, int sessionTimeout, Watcher watcher, boolean canBeReadOnly) canBeReadOnly:用于标识当前会话是否支持“read-only”(只读模式)。默认情况下,在Zookeeper集群中,一个机器如果和集群中过半及以上机器失去了网络连接,那么这个机器将不再处理客户端请求(包括读写请求)。但是在某些使用场景下,当ZooKeeper服务器发生此类故障的时候,我们还是希望Zookeeper服务器能够提供读服务。这就是Zookeeper的“read-only”模式。
ZooKeeper(String connectString, int sessionTimeout, Watcher watcher, long sessionId, byte[] sessionPasswd) sessionId:会话ID
sessionPasswd:会话秘钥
这两个参数能够唯一确定一个会话,同时客户端使用这两个参数可以实现客户端会话复用,从而达到恢复会话的效果。具体使用方法是,第一次连接上ZooKeeper服务器时,通过调用Zookeeper对象实例的以下两个接口,即可获得当前会话的ID和秘钥:
long getSessionId();
byte[] getSessionPasswd();
ZooKeeper(String connectString, int sessionTimeout, Watcher watcher, long sessionId, byte[] sessionPasswd, boolean canBeReadOnly)  

注:ZooKeeper客户端和服务端会话的建立是一个异步的过程。

2、创建节点

方法签名 参数解析
String create(final String path, byte data[], List<ACL> acl, CreateMode createMode) 返回创建的节点的实际路径
path:路径
data: 数据
acl:节点的ACL策略
createMode :创建模式        
        PERSISTENT  持久化目录节点
PERSISTENT_SEQUENTIAL  顺序自动编号的目录节点,这种目录节点会根据当前已近存在的节点数自动加 1
EPHEMERAL 临时目录节点,一旦创建这个节点的客户端与服务器端口也就是 session 超时,这种节点会被自动删除
EPHEMERAL_SEQUENTIAL  临时自动编号节点
void  create(String path, byte[] data, List<ACL> acl, CreateMode createMode, AsyncCallback.StringCallback cb, Object ctx)  异步的创建节点的方法
cb: 一个异步回调函数
ctx: 用于传递一个对象,可以在回调方法执行的时候使用,通常是放一个上下文(Context)信息

3、判断节点是否存在

方法签名 参数解析
 Stat exists(String path, Watcher watcher)   path:节点路径
watcher:注册的Watcher,用于监听以下三类事件:
节点被创建
节点被删除
节点被更新                                      
Stat exists(String path, boolean watch)                                                                
watcher:指定是否复用ZooKeeper中默认的Watcher            
void exists(String path, Watcher watcher, AsyncCallback.StatCallback cb, Object ctx)  异步的判断节点是否存在的方法    
cb:注册一个异步回调函数
ctx:用于传递上下文信息的对象
void exists(String path, boolean watch, AsyncCallback.StatCallback cb, Object ctx)  异步的判断节点是否存在的方法 

4、设置数据      

方法签名 参数解析
 Stat setData(String path, byte[] data, int version)  path:节点路径
data:数据
version:节点的版本,只有版本匹配上了才会修改。-1表示匹配所有版本                                         
void setData(String path, byte[] data, int version, AsyncCallback.StatCallback cb, Object ctx)  异步的设置数据的方法                                                                               

5、获取数据

方法签名 参数解析
void getData(String path, boolean watch, AsyncCallback.DataCallback cb, Object ctx)                                       异步的获取数据的方法                                                                                                                                                 
byte[] getData(String path, boolean watch, Stat stat)   
void getData(String path, Watcher watcher, AsyncCallback.DataCallback cb, Object ctx)  异步的获取数据的方法 
byte[] getData(String path, Watcher watcher, Stat stat)   


6、删除节点

方法签名 参数解析
 void  delete(String path, int version)   path:节点路径
version:节点的版本,只有版本匹配上了才会删除。-1表示匹配所有版本                                         
void delete(String path, int version, AsyncCallback.VoidCallback cb, Object ctx)  异步的删除节点的方法                                                                               

三、示例

package com.my.zktest;

import org.apache.zookeeper.*;

/**
 * Title: <br/>
 * Intention: <br/>
 * <p>
 * Class Name: com.my.zktest.TestZookeeper<br/>
 * Create Date: 2017/8/1 23:42 <br/>
 * Project Name: MyTest <br/>
 * Company:  All Rights Reserved. <br/>
 * Copyright © 2017 <br/>
 * </p>
 * <p>
 * author: GaoWei <br/>
 * 1st_examiner: <br/>
 * 2nd_examiner: <br/>
 * </p>
 *
 * @version 1.0
 * @since JDK 1.7
 */
public class TestZookeeper {

	public static void main(String[] args) throws Exception{
		ZooKeeper zk = new ZooKeeper("127.0.0.1:2181", 100, new Watcher() {
			public void process(WatchedEvent event) {
				System.out.println("node changes");
			}
		});
		String path = "/fruit";
		String returnPath = zk.create(path, "banana".getBytes("UTF-8"), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
		System.out.println("returnPath="+returnPath);
		System.out.println("创建节点" + path + ",数据为:" + new String(zk.getData(path, null, null), "UTF-8"));
		zk.setData(path, "orange".getBytes(), -1);
	}
}


参考:

1、http://ifeve.com/zookeeper-talk-quick-start/

2、http://www.cnblogs.com/ggjucheng/p/3370359.html

3、从PAXOS到ZOOKEEPER分布式一致性原理与实践.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章