首页 > 代码库 > zookeeper学习系列:二、api实践
zookeeper学习系列:二、api实践
上一章我们知道zookeeper的简介,启动,设置节点以及结构性能。本小节我们来玩玩api,获取下数据。
读一下:http://zookeeper.apache.org/doc/trunk/javaExample.html
然后我说 what the fuck it is?
我就想读个数据,需要这么复杂么。。。
动手改一下
版本1: 只获取数据,不管别的:
import org.apache.zookeeper.KeeperException;import org.apache.zookeeper.ZooKeeper;import java.io.IOException;public class ZkReader { public static void main(String[] args) throws IOException, InterruptedException, KeeperException { String hostPort = "192.168.1.2,192.168.1.3,192.168.1.4"; String znode = "/test"; ZooKeeper zk = new ZooKeeper(hostPort, 3000, null); System.out.println(new String(zk.getData(znode,false,null))); }}
在zkcli上创建 /test 并改变它的值:123,运行,输出:
123
能得到结果,但是报错了:
14/10/17 11:51:58 ERROR zookeeper.ClientCnxn: Error while calling watcher java.lang.NullPointerException at org.apache.zookeeper.ClientCnxn$EventThread.processEvent(ClientCnxn.java:521) at org.apache.zookeeper.ClientCnxn$EventThread.run(ClientCnxn.java:497)
看下源码,需要注册个watcher,意思是不这样zookeeper就只是个纯配置了?ok
版本2:zk get data+watcher
import org.apache.zookeeper.KeeperException;import org.apache.zookeeper.WatchedEvent;import org.apache.zookeeper.Watcher;import org.apache.zookeeper.ZooKeeper;import java.io.IOException;public class ZkReader { public static void main(String[] args) throws IOException, InterruptedException, KeeperException { String hostPort = "10.16.73.22,10.16.73.12,10.16.73.13"; String znode = "/test"; ZooKeeper zk = new ZooKeeper(hostPort, 3000, new MyWatcher()); System.out.println(new String(zk.getData(znode,false,null))); }}class MyWatcher implements Watcher { @Override public void process(WatchedEvent event) { System.out.println("hello zookeeper"); System.out.println(String.format("hello event! type=%s, stat=%s, path=%s",event.getType(),event.getState(),event.getPath())); }}
输出却是:
hello zookeeper
123
hello event! type=None, stat=SyncConnected, path=null
data总是在中间?百撕不得姐,在邮件组里咨询下,等答案
这两个版本只是做到了获取数据,如果数据有变动,需要自动更新呢?ok,看第三个版本:
zookeeper学习系列:二、api实践
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。