/** * new a watcher of path child * @param path the parent path * @param listener a listener * NOTE: * Only watch first level children, not recursive */ public ChildWatcher newChildWatcher(String path, ChildListener listener) { return newChildWatcher(path, listener, Boolean.TRUE); }
private void listenOnServerChanged() { zk.newChildWatcher(ZkPaths.SERVERS, new ChildListener() { @Override protected void onAdd(String path, byte[] data) { String server = ZkPaths.lastNode(path); client.addHttpServer(server); log.info("The server({}) joined.", server); } @Override protected void onDelete(String path) { String server = ZkPaths.lastNode(path); client.removeHttpServer(server); log.info("The server({}) left.", server); } }); }
@Override public void doStart(){ // watching the alive servers watcher = zk.client().newChildWatcher(ZkPaths.SERVERS, new ChildListener() { @Override protected void onAdd(String path, byte[] data) { String server = ZkPaths.lastNode(path); if (!alives.contains(server)){ alives.add(server); notifyListeners(server, true); Logs.info("The server ({}) is joined.", server); } } @Override protected void onDelete(String path) { String server = ZkPaths.lastNode(path); if(alives.remove(server)){ notifyListeners(server, false); Logs.warn("The server ({}) is left.", server); } } }); }
@Override public void doStart() { // listen app's clients change watcher = zk.client().newChildWatcher(ZkPaths.pathOfAppClients(appName), new ChildListener() { @Override protected void onAdd(String path, byte[] data) { // not started, or has shutdown // prevent multiple redundant notifies before started if (!started || shutdowned) { return; } String client = ZkPaths.lastNode(path); if (alives.contains(client)){ return; } alives.add(client); onClientChanged(appName, client, true); Logs.info("The app({})'s client({}) joined.", appName, client); } @Override protected void onDelete(String path) { String client = ZkPaths.lastNode(path); alives.remove(client); onClientChanged(appName, client, false); Logs.info("The app({})'s client({}) left.", appName, client); } }); }
@Override public void doStart() { String appName = client.getAppName(); String jobClass = getJobClass(); String jobInstancesNodePath = ZkPaths.pathOfJobInstances(appName, jobClass); this.watcher = client.getZk().newChildWatcher(jobInstancesNodePath, new ChildListener() { @Override protected void onAdd(String path, byte[] data) { // fired a new job instance String instanceId = ZkPaths.lastNode(path); if (Strings.isNullOrEmpty(instanceId)) return; // execute the job client.getJobExecutor().execute(Long.valueOf(instanceId), ZkJob.this); } }); }