import org.apache.zookeeper.*;
import java.io.IOException;
/**
* Created with IntelliJ IDEA.
* User: Administrator
* Date: 17-7-12
* Time: 下午3:03
* To change this template use File | Settings | File Templates.
*/
public class ZkWatchTest {
// 创建一个与服务器的连接
public static void main(String args[]) throws IOException, InterruptedException, KeeperException {
int sessionTime = 2000;
ZooKeeper zk = new ZooKeeper("10.2.4.12:2181,10.2.4.13:2181,10.2.4.14:2181", 3000, new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
System.out.println("已经触发了" + watchedEvent.getType() + "事件!");
}
});
// 创建一个目录节点
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();
}
}
zookeeper通知watcher
最新推荐文章于 2022-12-05 20:29:57 发布