首页 > 代码库 > 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实践