watch监听
watch特性
watch事件类型
watch事件捕获
watch监听连接状态
public class ZkConnectionWatcher implements Watcher {
//计数器对象
static CountDownLatch CountDownLatch=new CountDownLatch(1);
static ZooKeeper zooKeeper;
@Override
public void process(WatchedEvent event) {
if(event.getType()==Event.EventType.None){
if(event.getState()==Event.KeeperState.SyncConnected){
System.out.println("连接创建成功");
//唤醒线程
CountDownLatch.countDown();
}
if(event.getState()==Event.KeeperState.Disconnected){
System.out.println("断开连接");
}
if(event.getState()==Event.KeeperState.Expired){
System.out.println("会话超时");
}
if(event.getState()==Event.KeeperState.AuthFailed){
System.out.println("认证失败");
}
}
}
public static void main(String[] args) {
try{
zooKeeper = new ZooKeeper("192.168.164.134:2181", 5000, new ZkConnectionWatcher());
//阻塞线程直到连接成功被唤醒
CountDownLatch.await();
System.out.println(zooKeeper.getSessionId());
Thread.sleep(50000);
zooKeeper.close();
System.out.println("结束。。。。。。。。。。。。。。。。");
}catch (Exception e){
}
}
}
事件捕获之exists(检查节点是否存在)
exists监听有两种方式:1.使用连接对象watch2.自己重新定义一个watch
使用连接对象监听
public class ZkWatcherExists {
String IP="192.168.164.134:2181";
ZooKeeper zooKeeper=null;
//计数器
CountDownLatch countDownLatch=new CountDownLatch(1);
@Before
public void berfore() throws IOException {
zooKeeper= new ZooKeeper(IP, 5000, new Watcher() {
@Override
public void process(WatchedEvent event) {
System.out.println("连接对象参数");
if(event.getState()==Event.KeeperState.SyncConnected){
countDownLatch.countDown();
}
System.out.println("path="+event.getPath());
System.out.println("eventType="+event.getType());
}
});
}
@Test
public void test() throws KeeperException, InterruptedException {
zooKeeper.exists("/exists",true);
Thread.sleep(50000);
System.out.println("结束");
}
@After
public void after() throws InterruptedException {
zooKeeper.close();
}
}
自定义监听器
@Test
public void test2() throws KeeperException, InterruptedException {
zooKeeper.exists("/exists", new Watcher() {
@Override
public void process(WatchedEvent event) {
System.out.println("path="+event.getPath());
System.out.println("eventType="+event.getType());
}
});
Thread.sleep(50000);
System.out.println("结束");
}
watcher一次性
watcher失效后再次绑定
多监听器
事件捕获之getData()
使用连接对象监听
自定义监听器
watcher一次性
watcher失效后再次绑定
如果节点删除就不需要再次监听