ZooKeeper Java API
org.apache.zookeeper.ZookeeperZookeeper 是在Java中客户端主类,负责建立与zookeeper集群的会话,并提供方法进行操作。org.apache.zookeeper.WatcherWatcher接口表示一个标准的事件处理器,其定义了事件通知相关的逻辑,包含KeeperState和EventType两个枚举类,分别代表了通知状态和事件类型,同时定...
·
org.apache.zookeeper.Zookeeper
Zookeeper 是在Java中客户端主类,负责建立与zookeeper集群的会话,并提供方法进行操作。
org.apache.zookeeper.Watcher
Watcher接口表示一个标准的事件处理器,其定义了事件通知相关的逻辑,包含KeeperState和EventType两个枚举类,分别代表了通知状态和事件类型,同时定义了事件的回调方法:process(WatchedEvent event)。
process方法是Watcher接口中的一个回调方法,当ZooKeeper向客户端发送一个Watcher事件通知时,客户端就会对相应的process方法进行回调,从而实现对事件的处理。
基本使用
建立java maven项目,引入maven pom坐标。
pom文件
<dependencies>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.9</version>
</dependency>
</dependencies>
主类
import org.apache.zookeeper.*;
import org.apache.zookeeper.ZooDefs.Ids;
import java.io.IOException;
public class ZookeeperAPI {
public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
//初始化 ZooKeeper实例(zk地址、会话超时时间,与系统默认一致、watcher)
ZooKeeper zk = new ZooKeeper("node01:2181", 30000, new Watcher() {
public void process(WatchedEvent event) {
System.out.println("时间类型为:"+event.getType());
System.out.println("时间发生的路径:"+event.getPath());
System.out.println("通知状态为:"+event.getState());
}
});
zk.create("/myGirls","性感的".getBytes("utf-8"), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.close();
}
}
更多操作
import org.apache.zookeeper.*;
import org.apache.zookeeper.ZooDefs.Ids;
import java.io.IOException;
public class ZookeeperAPI2 {
public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
//初始化 ZooKeeper实例(zk地址、会话超时时间,与系统默认一致、watcher)
ZooKeeper zk = new ZooKeeper("node01:2181", 30000, new Watcher() {
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();
}
}
更多推荐
已为社区贡献5条内容
所有评论(0)