zookeeper 提供了java与C两种语言的客户端。我们学习的java的客户端使用,引入maven的jar包依赖。
<dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>3.5.8</version> </dependency>
客户端类:org.apache.zookeeper.ZooKeeper
实例化 Zookeeper 类之后将会自动与集群建立连接。构造方法的参数:
ZooKeeper zooKeeper = new ZooKeeper("192.168.1.1:2181", 4000, new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
}
});
create的参数说明:
public void create() throws KeeperException, InterruptedException {
int perm = ZooDefs.Perms.ADMIN | ZooDefs.Perms.READ; // ra
List<ACL> aclList = new ArrayList<>();
aclList.add(new ACL(perm, new Id("world", "anyone")));
aclList.add(new ACL(perm, new Id("ip", "127.0.0.1")));
String s = zooKeeper.create("/china/xi‘an", "Hel".getBytes(), aclList, CreateMode.PERSISTENT);
System.out.println(s);
}
getData 方法的参数:
注:所有的监听都是一次性的,如果要持续监听需要触发后在添加一次监听。
public void getData3() throws KeeperException, InterruptedException {
Stat stat = new Stat();
//获取节点数据时添加监听;当监听事件出发之后,再次去添加该监听
byte[] data = zooKeeper.getData("/china", new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
try {
//再次添加监听
zooKeeper.getData(watchedEvent.getPath(), this, null);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("listener: " + watchedEvent);
}
}, stat);
System.out.println(new String(data));
System.out.println(stat);
Thread.sleep(Long.MAX_VALUE);
}
getChildren 方法的参数:
public void getChild() throws KeeperException, InterruptedException {
List<String> children = zooKeeper.getChildren("/china", false, null);
children.stream().forEach(System.out::println);
}
ZkClient是由Datameer的工程师开发的开源客户端,它是在zookeeper客户端基础之上封装的,同时在内部实现了诸如session超时重连、watcher反复注册等功能,使用上更加方便;主要变化:
添加maven的jar包依赖:
<!--zkClient-->
<!-- https://mvnrepository.com/artifact/com.101tec/zkclient -->
<dependency>
<groupId>com.101tec</groupId>
<artifactId>zkclient</artifactId>
<version>0.11</version>
</dependency>
zkClient链接:
https://www.jianshu.com/p/d6de2d21d744
https://www.cnblogs.com/rouqinglangzi/p/11152580.html
https://www.cnblogs.com/xbq8080/p/6622606.html
path |
String |
|
watch |
boolean |
|
watcher |
Watcher |
|
cb |
Children2Callback |
|
ctx |
Object |
|
原文:https://www.cnblogs.com/yufeng218/p/13290581.html