开发者学堂课程【大数据 ZooKeeper 快速入门: Java API:watcher 操作】学习笔记,与课程紧密联系,让用户快速学习知识。
课程地址:https://developer.aliyun.com/learning/course/549/detail/7571
Java API:watcher 操作
目录:
一、创建目录节点
二、创建子目录节点
三、获取目录节点列表
四、修改子目录节点数据
课程概要:下面进行学习 zookeeper 的 JavaAPI 其他操作
zookeeper 其他操作示例
public static void main(String[] args) throws Exception{
//初始化ZooKeeper实例(zk地址、会话超时时间,与系统默认一致、watcher)
ZooKeeper zk = new ZooKeeper(
"node-21:2181, node-22: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("/testRootPathl"testRootData".getBytes
()
,Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
二、创建子目录节点
//创建一个子目录节点
zk.create("/testRootPath/testChildPathOne"
,
"testChildDataOnc".getBytes(),Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT) ;
System.out.println(new String(zk. getData("/testRootPath" , false, null)));
三、获取目录节点列表
//取出子目录节点列表
System.out. println(zk.getChildren(" /testRootPath",true)) ;
//获取数据
/**
@param path the given path
@param watch whether need to watch this node@param stat the stat of the node
return the data of the nodeI
@throws KeeperException If the server signals an error with a non-zero error code
@throws InterruptedException If the server transaction is interrupted.
*/
//监听打开相当于对节点 myGrils 设置了数据变化的监听,一旦节点数据改变,监听就会触发
Zk.getData(
“
myGrils
”
,true,NULL)
代码运行结果:
报错:节点以及存在,所有我们需要把创建节点的代码注释掉
//
zk.create("/
myGrils
"
,
"
性感的
"
.getBytes(),Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT) ;
重新运行代码:
四、修改子目录节点数据
//修改子目录节点数据
//一旦修改,监听就会生效,-1代表自己不维护,采用系统维护
zk.setData("/
myGrils
" ,"
美丽的
" .getBytes(),-1);
System. out.println("目录节点状态:["+zk.exists(" /testRootPath", true)+""]");
代码运行:
在 set 的时候发生监听,type 为数据节点改变
#shell 客户端查看
[zk:localhost:2181(CONNECTED) 21 ]get myGrils
运行结果:
运行结果:
美丽的
czxid =
0
x200000051
ctime = Thu an o416:04:25 cST 2018
mzxid =
0
x200000051
mtime = Thu an0416:04:25 cST 2018
pzxid =
0
x200000051
cversion =
0
dataversion =
0
ac1version =
0
ephemera1owner =
0
x
0
dataLength = 9
numchi1dren =
0
//创建另外一个子目录节点zk.create("/testRootPath/testChildPathTwo"","testChildDataTwo".getBytes(),lds.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT) ;