ZooKeeper-04-java 例子
2016年9月25日大约 9 分钟
一个简单的监视客户端
为了向您介绍ZooKeeper Java API,我们在这里开发了一个非常简单的监视客户端。
该ZooKeeper客户端监视znode的更改并通过启动或停止程序来响应。
要求
客户有四个要求:
它作为参数:
ZooKeeper服务的地址
znode的名称-要监视的znode的名称
将输出写入的文件名
带有参数的可执行文件。
它获取与znode关联的数据并启动可执行文件。
如果znode更改,则客户端将重新获取内容并重新启动可执行文件。
如果znode消失,则客户端将杀死可执行文件。
程序设计
按照惯例,ZooKeeper应用程序分为两个单元,一个单元维护连接,另一个单元监视数据。
在此应用程序中,名为Executor的类维护ZooKeeper连接,而名为DataMonitor的类监视ZooKeeper树中的数据。
另外,执行程序包含主线程并包含执行逻辑。
它负责根据znode的状态,与用户进行的交互很少,以及与您作为参数传入的可执行程序之间的交互,以及示例(根据要求)关闭并重新启动的示例。
maven 依赖
我们这里使用的是 zk 3.6.2,所以引入对应的 zk 依赖:
org.apache.zookeeper
zookeeper
3.6.2
执行者类
Executor对象是示例应用程序的主要容器。
如程序设计中所述,它同时包含ZooKeeper对象DataMonitor。
源码
// from the Executor class...
public static void main(String[] args) {
if (args.length 0) {
os.write(b, 0, rc);
}
} catch (IOException e) {
}
}
}
public void exists(byte[] data) {
if (data == null) {
if (child != null) {
System.out.println("Killing process");
child.destroy();
try {
child.waitFor();
} catch (InterruptedException e) {
}
}
child = null;
} else {
if (child != null) {
System.out.println("Stopping child");
child.destroy();
try {
child.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
FileOutputStream fos = new FileOutputStream(filename);
fos.write(data);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
System.out.println("Starting child");
child = Runtime.getRuntime().exec(exec);
new StreamWriter(child.getInputStream(), System.out);
new StreamWriter(child.getErrorStream(), System.err);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
DataMonitor.java
/**
* A simple class that monitors the data and existence of a ZooKeeper
* node. It uses asynchronous ZooKeeper APIs.
*/
import java.util.Arrays;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.AsyncCallback.StatCallback;
import org.apache.zookeeper.KeeperException.Code;
import org.apache.zookeeper.data.Stat;
public class DataMonitor implements Watcher, StatCallback {
ZooKeeper zk;
String znode;
Watcher chainedWatcher;
boolean dead;
DataMonitorListener listener;
byte prevData[];
public DataMonitor(ZooKeeper zk, String znode, Watcher chainedWatcher,
DataMonitorListener listener) {
this.zk = zk;
this.znode = znode;
this.chainedWatcher = chainedWatcher;
this.listener = listener;
// Get things started by checking if the node exists. We are going
// to be completely event driven
zk.exists(znode, true, this, null);
}
/**
* Other classes use the DataMonitor by implementing this method
*/
public interface DataMonitorListener {
/**
* The existence status of the node has changed.
*/
void exists(byte data[]);
/**
* The ZooKeeper session is no longer valid.
*
* @param rc
* the ZooKeeper reason code
*/
void closing(int rc);
}
public void process(WatchedEvent event) {
String path = event.getPath();
if (event.getType() == Event.EventType.None) {
// We are are being told that the state of the
// connection has changed
switch (event.getState()) {
case SyncConnected:
// In this particular example we don't need to do anything
// here - watches are automatically re-registered with
// server and any watches triggered while the client was
// disconnected will be delivered (in order of course)
break;
case Expired:
// It's all over
dead = true;
listener.closing(KeeperException.Code.SessionExpired);
break;
}
} else {
if (path != null && path.equals(znode)) {
// Something has changed on the node, let's find out
zk.exists(znode, true, this, null);
}
}
if (chainedWatcher != null) {
chainedWatcher.process(event);
}
}
public void processResult(int rc, String path, Object ctx, Stat stat) {
boolean exists;
switch (rc) {
case Code.Ok:
exists = true;
break;
case Code.NoNode:
exists = false;
break;
case Code.SessionExpired:
case Code.NoAuth:
dead = true;
listener.closing(rc);
return;
default:
// Retry errors
zk.exists(znode, true, this, null);
return;
}
byte b[] = null;
if (exists) {
try {
b = zk.getData(znode, false, null);
} catch (KeeperException e) {
// We don't need to worry about recovering now. The watch
// callbacks will kick off any exception handling
e.printStackTrace();
} catch (InterruptedException e) {
return;
}
}
if ((b == null && b != prevData)
|| (b != null && !Arrays.equals(prevData, b))) {
listener.exists(b);
prevData = b;
}
}
}
参考资料
https://zookeeper.apache.org/doc/r3.6.2/zookeeperStarted.html
https://mvnrepository.com/artifact/org.apache.zookeeper/zookeeper
贡献者
binbin.hou