zookeeper有点像微信公众号平台的功能。你向公众号平台查询某个或者某类平台,平台反馈给你有关信息。然后你关注了某个公众号,然后这个公众号的变动就将由公众号平台推送给你。
在分布式应用中,zookeeper管理各个应用在集群注册自己的信息及变动,集群则将有关信息推送给“订阅”这些信息的客户端(所谓的watch监听机制)
一、数据的增删改查
1、在命令行环境下zookeeper自带的客户端zkCli.sh的操作
1)创建节点
create /node1 abc
create /node1/a a
2)获取节点数据
get /node1
3)修改数据
set /node1 efg
.....
2、在java 原生 api中的操作
ZooKeeper zooKeeper = new ZooKeeper("192.168.124.11:2181,192.168.124.18:2181,192.168.124.14:2181", 4000, null);
// zooKeeper.create("/node1","1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
//Stat exists = zooKeeper.exists("/node1", null);
//System.out.println(exists.toString());
List<String> children = zooKeeper.getChildren("/node1", null);
for(String child:children)
System.out.println(child);
二、监听机制
当数据或者节点信息变动时,zookeeper集群会向设立了监听信息的客户端发送有关信息。
1、在zkCli.sh的操作
1) 监听节点变动 ls -w path w代表watch
2)获取节点数据变动 get -w path
2、在java 原生api的操作,增加一个Watcher对象,即可设置监听。
ZooKeeper zooKeeper = new ZooKeeper("192.168.124.11:2181,192.168.124.18:2181,192.168.124.14:2181", 4000, new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
System.out.println("正在监听");
}
});
//监听节点
zooKeeper.getChildren("/node1", new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
//监听路径
System.out.println(watchedEvent.getPath());
//监听类型
System.out.println(watchedEvent.getType());
System.out.println("节点被修改了");
}
});
Thread.sleep(Long.MAX_VALUE);
//监听数据
zooKeeper.getData("/node1", new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
System.out.println(watchedEvent.getPath());
System.out.println(watchedEvent.getType());
System.out.println("节点数据被修改了");
}
},null);
zookeeper操作的高级工具:
zkclient
apache 的 Curator