1 导入相关的pom依赖
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.9</version>
</dependency>
2 编写代码,完成CURD
public static void main(String[] args) throws Exception {
// 初始化 ZooKeeper 实例(zk 地址、会话超时时间,与系统默认一致、watcher)
ZooKeeper zk = new ZooKeeper("192.168.44.41:2181,192.168.44.42:2181,192.168.44.43:2181", 30000, new Watcher() {
@Override
public void process(WatchedEvent event) {
System.out.println("事件类型为:" + event.getType());
System.out.println("事件发生的路径:" + event.getPath());
System.out.println("通知状态为:" + event.getState());
}
});
// 创建一个目录节点
zk.create("/testRootPath", "testRootData".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
// 创建一个子目录节点
zk.create("/testRootPath/testChildPathOne", "testChildDataOne".getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
System.out.println(new String(zk.getData("/testRootPath", false, null)));
// 取出子目录节点列表
System.out.println(zk.getChildren("/testRootPath", true));
// 修改子目录节点数据
zk.setData("/testRootPath/testChildPathOne", "modifyChildDataOne".getBytes(), -1);
System.out.println("目录节点状态:[" + zk.exists("/testRootPath", true) + "]");
// 创建另外一个子目录节点
zk.create("/testRootPath/testChildPathTwo", "testChildDataTwo".getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
System.out.println(new String(zk.getData("/testRootPath/testChildPathTwo", true, null)));
// 删除子目录节点
zk.delete("/testRootPath/testChildPathTwo", -1);
zk.delete("/testRootPath/testChildPathOne", -1);
// 删除父目录节点
zk.delete("/testRootPath", -1);
zk.close();
}
3 编写代码,完成监听及永久监听
public class ZkWatcherDemo {
static ZooKeeper zk = null;
public static void main(String[] args) throws Exception {
// 初始化 ZooKeeper 实例(zk 地址、会话超时时间,与系统默认一致、watcher)
zk = new ZooKeeper("192.168.44.41:2181,192.168.44.42:2181,192.168.44.43:2181", 30000, new Watcher() {
@Override
public void process(WatchedEvent event) {
System.out.println("事件类型为:" + event.getType());
System.out.println("事件发生的路径:" + event.getPath());
System.out.println("通知状态为:" + event.getState());
//如果要想实现永久监听 在上一次监听回调之后再次设置同样的监听 以此达到前后两个监听首尾相连
try {
zk.getData("/zkbyjava", true, null);
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// zkClient.create("/zkbyjava2","么么哒".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
//在获取数据的时候 通过第二个参数开启了监听 监听这个节点的数据是否改变
byte[] data = zk.getData("/zkbyjava", true, null);
//-1表示由zk管理数据版本号
zk.setData("/zkbyjava", "呵呵哒1".getBytes(), -1);
//再次修改数据
zk.setData("/zkbyjava", "呵呵哒2".getBytes(), -1);
zk.close();
}
}