为了完成本关任务,你需要掌握: 1.ZooKeeper 对象实例化方法; 2.节点同步与异步的创建、删除方法; 3.节点数据获取方法; 4.ZooKeeper 对象包含的 API 含义使用方法。
节点数据获取
前两节实训中,我们学习了如何创建、关闭会话,如何创建、删除节点的同步和异步调用方法。本实训基于前两节实训,介绍节点获取的方法。节点获取同样有同步和异步调用的方法。
同步调用有以下两种:
byte[] getData(String path, boolean watch, Stat stat)
byte[] getData(String path, Watcher watcher, Stat stat)
同样,异步调用也有以下两种方法:
void getData(String path, boolean watch, DataCallback cb, Object ctx)
void getData(String path, Watcher watcher, DataCallback cb, Object ctx)
以上方法中的参数含义如下:
path:指定数据节点的节点路径;
watcher:注册的 watcher,一旦注册节点内容有变更,就会向客户端发送通知,该参数允许传入 null;
stat:指定数据节点的节点状态信息,用法是在接口中传入一个旧的 stat 变量,该 stat 变量会在方法执行过程中,被来自服务端响应的新 stat 对象替换;
Watch:表明是否需要注册一个 watcher;
cb:注册一个异步回调函数;
ctx:节点名称。
同步节点获取使用示例:
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;import java.io.IOException;public class MyTest {
private ZooKeeper zk;
// 实现一个 Watcher
private Watcher wh = new Watcher() {
// 重写 process 方法
public void process(WatchedEvent event) {
System.out.println(event);
}
};// 连接 ZooKeeper 服务器
public void createZKInstance() throws IOException {
zk = new ZooKeeper("localhost:2181", 15000, this.wh);
}// 同步创建节点
public String createNode() throws IOException, KeeperException, InterruptedException {
String ephemeralPath = zk.create("/zk-test-create-ephemeral", "ephemeral".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
return ephemeralPath;
}// 同步获取节点数据
public void getData() throws IOException, KeeperException, InterruptedException {
Stat stat = new Stat();
byte[] data = zk.getData("/zk-test-create-ephemeral", wh, stat);
System.out.println(new String(data));
}
public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
MyTest myTest = new MyTest();
// 连接 ZooKeeper 服务器
myTest.createZKInstance();
// 同步创建节点
myTest.createNode();
// 同步获取节点数据
myTest.getData();}}
执行结果:
WatchedEvent state:SyncConnected type:None path:null
ephemeral
上述代码中,我们首先通过 new Stat() 创建一个 stat 对象,然后把该对象传入 getData() 方法中,同步获取 /zk-test-create-ephemeral 节点中的数据“ephemeral”。
编程要求
仔细阅读右侧编辑区内给出的代码框架及注释,在 Begin-End 间编写程序代码,在 getData 方法中同步获取 /myzk 节点数据(需要实现 Watcher 监视)。
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;import java.io.IOException;public class Student {// 初始化 ZooKeeper 实例private ZooKeeper zk;// 实现一个 Watcherprivate Watcher wh = new Watcher() {// 重写 process 方法public void process(WatchedEvent event) {System.out.println(event);}};// 连接 ZooKeeper 服务器public ZooKeeper createZKInstance() throws IOException {zk = new ZooKeeper("localhost:2181", 15000, this.wh);return zk;}// 同步获取节点数据public void getData() throws IOException, KeeperException, InterruptedException {// 请在此处编写代码/********* Begin *********/Stat stat = new Stat(); byte[] data = zk.getData("/myzk", wh, stat); System.out.println(new String(data)); /********* End *********/}}