zookeeperclient设置监听

时间:2022-12-31 14:11:56

1、目的

zookeeper是一个分布式服务管理框架。zookeeper提供了对client的通知。即在server端的节点有改动或者删除的时候,能够给client进行通知。

2、server端部署

server端部署zookeeper的步骤省略。详细的能够參看我前面的文章。部署也比較简单。

3、client接收通知代码

import java.io.IOException;
import java.util.List; import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper; class Wa implements Runnable
{ public void run() {
//连接启动k
try {
ZooKeeper zk = new ZooKeeper("10.218.137.73:2181", 500000,new Watcher() {
// 监控全部被触发的事件
public void process(WatchedEvent event) {
System.out.println("changing...");
}
});
//设置监听器
Watcher wc = new Watcher() { public void process(WatchedEvent event) {
// TODO Auto-generated method stub
if (event.getType() == EventType.NodeDataChanged) {
System.out.println("change");
}
if (event.getType() == EventType.NodeDeleted){
System.out.println("dele");
}
if(event.getType()== EventType.NodeCreated){
System.out.println("create");
}
} };
//进行轮询。当中exists方法用来询问状态,而且设置了监听器,假设发生变化,则会回调监听器里的方法。 while(true)
{
zk.exists("/jianghuiwen", wc);
} } catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (KeeperException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} } } public class Main { public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
// TODO Auto-generated method stub Thread t = new Thread(new Wa());
t.start();
} }

直接贴了代码,没有加上各种jar包,假设同学们要执行的话,须要先设置一下相关的jar包。应该就是Log4j和zookeeper的包。

4、測试

利用zookeeper自带的zkCli.sh或者用其它对节点进行改动的client进行改动节点。能够发现我们得到了以下的输出:

zookeeperclient设置监听