zookeeper-watcher- 简单例子

zookeeper watcher示例

示例说明:zookeeper server端,client端每100毫秒写入数据,另一个client端watch节点数据变化。

server端
参考这篇的server端。
[url]http://xkorey.iteye.com/blog/2201301[/url]

数据生成端

public void increase(){
int inx=0;
try {
zk = new ZooKeeper("localhost:22801",2000,new ZKWatcher());
if(zk.exists(path,false)==null){
zk.create(path,new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
}
while (run){
zk.setData(path,(""+(inx++)).getBytes(),-1);
Thread.sleep(100);
}
System.out.println("maker ext. the value is:"+inx);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (KeeperException e) {
e.printStackTrace();
}


watch端


public class ZKEventCatcher implements Watcher, AsyncCallback.StatCallback{

String path = "/test_data_increase";
ZooKeeper zk=null;
Object o =new Object();

public void init(){
try {
zk = new ZooKeeper("localhost:8610",3000,this);
zk.exists(path,this);
synchronized (o){
o.wait();
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}

public void processResult(int i, String s, Object o, Stat stat) {
boolean exists;
switch (KeeperException.Code.get(i)) {
case OK:
exists = true;
break;
case NONODE:
exists = false;
break;
case SESSIONEXPIRED:
case NOAUTH:
return;
default:
zk.exists(s, true, this, stat);
return;
}
if(exists){
try {
String val = new String(zk.getData(path,false,null));
System.out.println(val);
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public void process(WatchedEvent event) {
String path = event.getPath();
if (event.getType() == Event.EventType.None) {
switch (event.getState()) {
case SyncConnected:
break;
case Expired:
break;
}
} else {
if (path != null) {
zk.exists(path, true, this, null);
}
}
}

public static void main(String[]args){
ZKEventCatcher catcher = new ZKEventCatcher();
catcher.init();
}
}


监听的结果是得到的数值是连续的、和数据生成端是一致的,并没有出现数值跳跃的情况。

结论:只要实现Watcher, AsyncCallback.StatCallback2 个类的方法。节点值变化zookeeper会触发这2个回调函数。所以只要在一开始exists的watcher设定为自己(this)。然后wait()就可以了。

官方链接:
[url]http://zookeeper.apache.org/doc/trunk/javaExample.html[/url]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值