添加Maven依赖
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.11</version>
</dependency>
创建Zookeeper连接
创建Zookeeper连接的构造函数如下
public ZooKeeper(String connectString, int sessionTimeout, Watcher watcher,boolean canBeReadOnly)
其中:
- connectString:包括主机名和端口号
- sessionTimeout:以毫秒为单位,表示Zookeeper等待客户端通信的最长时间,客户端如果超过这个时间没有和服务端进行通信,那么就认为该客户端已终止,一般设置值5~10s
- watcher:用于接收会话事件的接口,需要自己定义,实现process()方法
- canBeReadOnly:客户端是否只读模式
代码示例:
/**
* @author Eason
* @create 2018-04-05 15:40
**/
public class Connection implements Watcher {
private static final int DEFAULT_SESSIONTIMEOUT = 5 * 1000;
private final String connectionString;
private final int sessionTimeout;
private ZooKeeper zooKeeper;
private volatile boolean connected;
public boolean isConnected() {
return connected;
}
public ZooKeeper getZooKeeper() {
return zooKeeper;
}
public String getConnectionString() {
return connectionString;
}
public int getSessionTimeout() {
return sessionTimeout;
}
public Connection(String connectionString, int sessionTimeout) {
this.connectionString = connectionString;
this.sessionTimeout = sessionTimeout;
try {
zooKeeper = new ZooKeeper(connectionString, sessionTimeout, this, false);
connected = true;
} catch (IOException e) {
throw new ZkConnectionException("Create Zookeeper Exception : " + e);
}
}
public Connection(String connectionString) {
this(connectionString, DEFAULT_SESSIONTIMEOUT);
}
public void process(WatchedEvent event) {
System.out.println(event);
//TODO://
}
public static void main(String[] args) {
String connectionString = "192.168.1.6:2181,192.168.1.6:2182,192.168.1.6:2183";
Connection connection = new Connection(connectionString);
while (connection.isConnected()){
}
}
}
执行main方法后输出:
2018-04-05 17:07:56,755 INFO [org.apache.zookeeper.ZooKeeper] - Client environment:zookeeper.version=3.4.11-37e277162d567b55a07d1755f0b31c32e93c01a0, built on 11/01/2017 18:06 GMT
2018-04-05 17:07:56,756 INFO [org.apache.zookeeper.ZooKeeper] - Client environment:host.name=192.168.1.5
2018-04-05 17:07:56,757 INFO [org.apache.zookeeper.ZooKeeper] - Client environment:java.version=1.8.0_141
2018-04-05 17:07:56,757 INFO [org.apache.zookeeper.ZooKeeper] - Client environment:java.vendor=Oracle Corporation
....
2018-04-05 17:07:56,758 INFO [org.apache.zookeeper.ZooKeeper] - Initiating client connection, connectString=192.168.1.6:2181,192.168.1.6:2182,192.168.1.6:2183 sessionTimeout=5000 watcher=com.yin.myproject.zookeeper.Connection@5910e440
2018-04-05 17:07:56,762 DEBUG [org.apache.zookeeper.ClientCnxn] - zookeeper.disableAutoWatchReset is false
2018-04-05 17:07:57,618 INFO [org.apache.zookeeper.ClientCnxn] - Opening socket connection to server 192.168.1.6/192.168.1.6:2181. Will not attempt to authenticate using SASL (unknown error)
2018-04-05 17:07:57,630 INFO [org.apache.zookeeper.ClientCnxn] - Socket connection established to 192.168.1.6/192.168.1.6:2181, initiating session
2018-04-05 17:07:57,633 DEBUG [org.apache.zookeeper.ClientCnxn] - Session establishment request sent on 192.168.1.6/192.168.1.6:2181
2018-04-05 17:07:57,668 INFO [org.apache.zookeeper.ClientCnxn] - Session establishment complete on server 192.168.1.6/192.168.1.6:2181, sessionid = 0x1000073c1de0002, negotiated timeout = 5000
WatchedEvent state:SyncConnected type:None path:null
2018-04-05 17:07:59,312 DEBUG [org.apache.zookeeper.ClientCnxn] - Got ping response for sessionid: 0x1000073c1de0002 after 5ms
...
创建Zookeeper节点
Zookeeper的数据结构模型可以分为以下四类:
1. 临时无序节点
2. 临时有序节点
3. 持久无序节点
4. 持久有序节点
临时节点的两个特性:
1. 创建该节点的客户端终止连接,则临时节点被删除
2. 临时节点下面不能创建子节点有序节点的特点:可以创建相同路径的节点,但是节点后面会自动追加数字表名顺序性
API中创建节点的方法
public String create(final String path, byte data[], List<ACL> acl,CreateMode createMode)
其中
- path:节点路径
- data[]:节点上存放值得字节数组
- acl:权限控制,可取值在ZooDefs.Ids中有详细定义
- createMode:是否为临时节点,可取值为:PERSISTENT(持久无序)PERSISTENT_SEQUENTIAL(持久有序) EPHEMERAL(临时无序) EPHEMERAL_SEQUENTIAL(临时有序)
/**
* 创建持久性无序节点
* @param path
* @param value
* @return 如果返回值为null, 说明创建失败
*/
public String createNode(String path, String value) {
try {
return zooKeeper.create(path, value.getBytes(), OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
/**
* 创建临时无序节点
*
* @param path
* @param value
* @return 如果返回值为null, 说明创建失败
*/
public String createEphemeralNode(String path, String value) {
try {
return zooKeeper.create(path, value.getBytes(), OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
/**
* 创建临时有序节点
*
* @param path
* @param value
* @return 如果返回值为null, 说明创建失败
*/
public String createEphemeralSequentialNode(String path, String value) {
try {
return zooKeeper.create(path, value.getBytes(), OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
/**
* 创建持久有序节点
*
* @param path
* @param value
* @return 如果返回值为null, 说明创建失败
*/
public String createSequentialNode(String path, String value) {
try {
return zooKeeper.create(path, value.getBytes(), OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
main方法测试:
public static void main(String[] args) {
String connectionString = "192.168.1.6:2181,192.168.1.6:2182,192.168.1.6:2183";
Connection connection = new Connection(connectionString);
connection.createNode("/path1","test");
connection.createSequentialNode("/path2","test");
connection.createSequentialNode("/path2","test");
connection.createEphemeralNode("/path3","test");
connection.createEphemeralSequentialNode("/path4","test");
connection.createEphemeralSequentialNode("/path4","test");
while (connection.isConnected()){
}
}
控制台输出:
2018-04-05 18:04:00,610 INFO [org.apache.zookeeper.ClientCnxn] - Opening socket connection to server 192.168.1.6/192.168.1.6:2182. Will not attempt to authenticate using SASL (unknown error)
2018-04-05 18:04:00,641 INFO [org.apache.zookeeper.ClientCnxn] - Socket connection established to 192.168.1.6/192.168.1.6:2182, initiating session
2018-04-05 18:04:00,641 DEBUG [org.apache.zookeeper.ClientCnxn] - Session establishment request sent on 192.168.1.6/192.168.1.6:2182
2018-04-05 18:04:00,703 INFO [org.apache.zookeeper.ClientCnxn] - Session establishment complete on server 192.168.1.6/192.168.1.6:2182, sessionid = 0x2000073c2770003, negotiated timeout = 5000
WatchedEvent state:SyncConnected type:None path:null
2018-04-05 18:04:00,758 DEBUG [org.apache.zookeeper.ClientCnxn] - Reading reply sessionid:0x2000073c2770003, packet:: clientPath:null serverPath:null finished:false header:: 1,1 replyHeader:: 1,4294967325,0 request:: '/path1,#74657374,v{s{31,s{'world,'anyone}}},0 response:: '/path1
2018-04-05 18:04:00,794 DEBUG [org.apache.zookeeper.ClientCnxn] - Reading reply sessionid:0x2000073c2770003, packet:: clientPath:null serverPath:null finished:false header:: 2,1 replyHeader:: 2,4294967326,0 request:: '/path2,#74657374,v{s{31,s{'world,'anyone}}},3 response:: '/path20000000007
2018-04-05 18:04:00,841 DEBUG [org.apache.zookeeper.ClientCnxn] - Reading reply sessionid:0x2000073c2770003, packet:: clientPath:null serverPath:null finished:false header:: 3,1 replyHeader:: 3,4294967327,0 request:: '/path2,#74657374,v{s{31,s{'world,'anyone}}},3 response:: '/path20000000008
2018-04-05 18:04:00,882 DEBUG [org.apache.zookeeper.ClientCnxn] - Reading reply sessionid:0x2000073c2770003, packet:: clientPath:null serverPath:null finished:false header:: 4,1 replyHeader:: 4,4294967328,0 request:: '/path3,#74657374,v{s{31,s{'world,'anyone}}},1 response:: '/path3
2018-04-05 18:04:00,926 DEBUG [org.apache.zookeeper.ClientCnxn] - Reading reply sessionid:0x2000073c2770003, packet:: clientPath:null serverPath:null finished:false header:: 5,1 replyHeader:: 5,4294967329,0 request:: '/path4,#74657374,v{s{31,s{'world,'anyone}}},3 response:: '/path40000000010
2018-04-05 18:04:00,971 DEBUG [org.apache.zookeeper.ClientCnxn] - Reading reply sessionid:0x2000073c2770003, packet:: clientPath:null serverPath:null finished:false header:: 6,1 replyHeader:: 6,4294967330,0 request:: '/path4,#74657374,v{s{31,s{'world,'anyone}}},3 response:: '/path40000000011