Java tutorial
/** *Copyright 2016 zhaojie * *Licensed under the Apache License, Version 2.0 (the "License"); *you may not use this file except in compliance with the License. *You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * *Unless required by applicable law or agreed to in writing, software *distributed under the License is distributed on an "AS IS" BASIS, *WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *See the License for the specific language governing permissions and *limitations under the License. */ package com.api6.zkclient.watcher; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.Watcher.Event.EventType; import org.apache.zookeeper.Watcher.Event.KeeperState; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.api6.zkclient.ZKClient; /** * ?? * @author: zhaojie/zh_jie@163.com.com */ public class ZKWatcher implements Watcher { private static final Logger LOG = LoggerFactory.getLogger(ZKWatcher.class); private final ZKClient client; private final ZKWatcherProcess process; public ZKWatcher(ZKClient client) { this.client = client; this.process = new ZKWatcherProcess(client); } /** * ? * @see org.apache.zookeeper.Watcher#process(org.apache.zookeeper.WatchedEvent) */ @Override public void process(WatchedEvent event) { LOG.debug("ZooKeeper event is arrived [" + event + " ]..."); EventType eventType = event.getType(); //? boolean stateChanged = event.getPath() == null; // boolean znodeChanged = event.getPath() != null; //??? boolean nodeChanged = eventType == EventType.NodeDataChanged || eventType == EventType.NodeDeleted || eventType == EventType.NodeCreated; //??????????? boolean childChanged = eventType == EventType.NodeDeleted || eventType == EventType.NodeCreated || eventType == EventType.NodeChildrenChanged; client.acquireEventLock(); try { if (client.getShutdownTrigger()) { LOG.debug("client will shutdown,ignore the event [" + eventType + " | " + event.getPath() + "]"); return; } if (stateChanged) {//ZooKeeper??? process.processStateChanged(event); } if (nodeChanged) {//?????? process.processNodeChanged(event); } if (childChanged) {//?????????? process.processChildChanged(event); } } finally { if (stateChanged) { client.getEventLock().getStateChangedCondition().signalAll(); // ????watch. // ???????? // ???? if (event.getState() == KeeperState.Expired) { client.getEventLock().getNodeEventCondition().signalAll(); client.getEventLock().getNodeOrChildChangedCondition().signalAll(); // ???? process.processAllNodeAndChildListeners(event); } } if (znodeChanged) { client.getEventLock().getNodeEventCondition().signalAll(); } if (nodeChanged || childChanged) { client.getEventLock().getNodeOrChildChangedCondition().signalAll(); } client.releaseEventLock(); } } /** * ?? * @return void */ public void stop() { process.stop(); } }