watche
依赖包
<dependency>
<groupId>com.101tec</groupId>
<artifactId>zkclient</artifactId>
<version>0.10</version>
</dependency>
代码示例
public class Test implements Watcher {
static ZooKeeper zooKeeper;
static {
try {
//传入test类,目的是使用test类中的process监听节点变化
zooKeeper = new ZooKeeper("123.206.34.40:2181", 15000, new Test());
} catch (IOException e) {
e.printStackTrace();
}
}
//实现Watcher,重写process,用于监听节点变化
@Override
public void process(WatchedEvent event) {
System.out.println("eventType:" + event.getType());
System.out.println("eventPath:" + event.getPath());
System.out.println("eventToString:" + event.toString());
System.out.println("------------------------");
//默认只监听一次,这里实现重复监听
if (event.getType() == Event.EventType.NodeDataChanged) {
try {
zooKeeper.exists(event.getPath(), true);
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//getData()/ exists /getChildren
public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
//Curator
String path = "/watcher";
//false表示只做判断,不设置监听
if (zooKeeper.exists(path, false) == null) {
//创建一个持久化节点,赋value值为0,权限放开
zooKeeper.create("/watcher", "0".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
Thread.sleep(1000);
zooKeeper.exists(path, true); //true表示使用zookeeper实例中配置的watcher
// Thread.sleep(1000);
// zooKeeper.setData("/watch", "1".getBytes(),-1) ; // 修改节点的值触发监听
System.in.read();
}
}
上面的代码示例中的注释已经解释了如何去连接zookeeper并监听节点变化,当监听到目标节点的变化后,由process来监听节点变化类型以及实现业务逻辑。
linux连接zookeeper,sh zkCli.sh -server 127.0.0.1:2181,并在zookeeper上修改节点,查看监听结果