基本使用
maven的pom依赖
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.9</version>
</dependency>
java代码
public class ZKClient { static ZooKeeper zk = null; public static void main(String[] args) throws Exception { //第一个参数:zk集群地址 host:port,多个地址之间用英文逗号分隔
//第二个参数:连接会话超时时间 单位为毫秒
//第三个参数:匿名new接口 监听
zk = new ZooKeeper("node-1:2181,node-2:2181,node-3:2181", 30000, new Watcher() {
//该方法为监听触发是回调的方法
public void process(WatchedEvent event) {
int i = 0;
System.out.println(++i);
System.out.println(event.getPath());
System.out.println(event.getType());
System.out.println(event.getState());
//实现永久监听
try {
zk.getData("/itcastbyjava2", true, null);
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// zk.create("/itcastbyjava2","123321".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); //设置监听
zk.getData("/itcastbyjava2", true, null); zk.setData("/itcastbyjava2", "456".getBytes(), -1);
zk.setData("/itcastbyjava2", "789".getBytes(), -1); zk.close();
}
}
其他操作
public static void main(String[] args) throws Exception {
// 初始化 ZooKeeper 实例(zk 地址、会话超时时间,与系统默认一致、watcher)
ZooKeeper zk = new ZooKeeper("node-1:2181,node-2:2181,node-3: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(), Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
// 创建一个子目录节点
zk.create("/testRootPath/testChildPathOne", "testChildDataOne".getBytes(),
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(),
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();
}