package check;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
public class Executor
implements Watcher, Runnable, DataMonitor.DataMonitorListener
{
String znode;
DataMonitor dm;
ZooKeeper zk;
String filename;
String exec[];
Process child;
public Executor(String hostPort, String znode, String filename,
String exec[]) throws KeeperException, IOException {
this.filename = filename;
this.exec = exec;
zk = new ZooKeeper(hostPort, 3000, this);//自己就是一个watcher
dm = new DataMonitor(zk, znode, null, this);
}
/**
* @param args
*/
public static void main(String[] args) {
// if (args.length < 4) {
// System.err
// .println("USAGE: Executor hostPort znode filename program [args ...]");
// System.exit(2);
// }
String hostPort = "";
String znode = "/root/child1";//args[1];
String filename = "learnzookeeperFile";
String exec[] = new String[200 - 3];
String[] args1 = {
"192.168.*。*",
"/root/child1",
"learnzookeeperFile"
};
//System.arraycopy(args, 3, exec, 0, exec.length);//需要了解一下字符串数组是怎么一回事。
try {
new Executor(hostPort, znode, filename, exec).run();
} catch (Exception e) {
e.printStackTrace();
}
}
/***************************************************************************
* We do process any events ourselves, we just need to forward them on.
*
* @see org.apache.zookeeper.Watcher#process(org.apache.zookeeper.proto.WatcherEvent)
*/
public void process(WatchedEvent event) {
dm.process(event);
}
public void run() {
try {
synchronized (this) {
int num = 0;
while (!dm.dead) {
//为什么仅仅执行了一次。
System.out.println("Executor::run times: " + num++);
wait();//这句话的含义
}
}
} catch (InterruptedException e) {
}
}
public void closing(int rc) {
synchronized (this) {
notifyAll();
}
}
static class StreamWriter extends Thread {
OutputStream os;
InputStream is;
StreamWriter(InputStream is, OutputStream os) {
this.is = is;
this.os = os;
start();
}
public void run() {
byte b[] = new byte[80];
int rc;
try {
while ((rc = is.read(b)) > 0) {
os.write(b, 0, rc);
}
} catch (IOException e) {
}
}
}
public void exists(byte[] data) {
System.out.println("Executor::exist start");
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 (Exception e) {
e.printStackTrace();
}
}
}
}
<pre name="code" class="java">package check;
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
// 后续需要打开,
System.out.println("DataMoitor::constor");
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) {
System.out.println("DataMonitor process start.");
String path = event.getPath();
System.out.println(path);
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);
}
}
//这个是系统内部的调用机制, 第一次是因为eixits调用的,第二次是在哪里调用呢?
public void processResult(int rc, String path, Object ctx, Stat stat) {
System.out.println("DataMonitor::processResult>>>start");
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;
}
}
}
package check;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
//
//import org.apache.commons.logging.Log;
//import org.apache.commons.logging.LogFactory;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.Watcher.Event.KeeperState;
public class absZookeeper implements Watcher{
private static int sessionTime = 3000;
protected ZooKeeper zookeeper;
protected CountDownLatch countDownLatch=new CountDownLatch(1);
public void connect(String con){
try {
zookeeper = new ZooKeeper(con, sessionTime, this);
countDownLatch.await();//为什么
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void process(WatchedEvent event) {
if(event.getState()==KeeperState.SyncConnected){
countDownLatch.countDown();
}
}
public void close(){
try {
zookeeper.close();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}<pre name="code" class="java">package check;
import java.util.List;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs.Ids;
public class zookeeperCheckImpl extends absZookeeper{
public void create(String path, byte[] data){
try {
this.zookeeper.create(path, data, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
} catch (KeeperException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void getChild(String path){
try {
List<String> childList = this.zookeeper.getChildren(path,false);
if(childList.isEmpty()){
System.out.println("no node in the path");
}
for(String ele : childList){
System.out.println("the node is " + ele);
}
} catch (KeeperException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void modifyData(String path, String valueModified){
//修改相关内容
//ok
try {
this.zookeeper.setData(path, valueModified.getBytes(), this.zookeeper.exists(path, true).getVersion());
} catch (KeeperException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void deleteNode(String path){
try {
this.zookeeper.delete(path, this.zookeeper.exists(path, true).getVersion());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (KeeperException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String args[]){
//
//create node.
//加入显示节点的
zookeeperCheckImpl checkSample = new zookeeperCheckImpl();
checkSample.connect("192.168.130.174");
//checkSample.getChild("/root");
byte[] data = new byte[]{'a', 'b', 'c'};//byte 的装箱对象是什么呢?
//checkSample.create("root/child1", data);
checkSample.create("/root", data);
String child1 = "child1";
checkSample.create("/root/child1", child1.getBytes());
String child2 = "child2";
checkSample.create("/root/child2", child2.getBytes());
String child3 = "child3";
checkSample.create("/root/child3", child3.getBytes());
checkSample.getChild("/root");
checkSample.modifyData("/root/child1", "modified1");
//这个看需要改成可以配置的
//checkSample.deleteNode("/root/child1");
//checkSample.deleteNode("/root/child2");
//checkSample.deleteNode("/root/child3");
//checkSample.deleteNode("/root");
checkSample.close();
}
}
在学习zookeeper , 稍显复杂的示例代码不多,以zookeeper官方的示例代码为基础,并进行了改进。具体改进是增加了生成树的功能,并且动态改变树上节点的值。
package check;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
public class Executor
implements Watcher, Runnable, DataMonitor.DataMonitorListener
{
String znode;
DataMonitor dm;
ZooKeeper zk;
String filename;
String exec[];
Process child;
public Executor(String hostPort, String znode, String filename,
String exec[]) throws KeeperException, IOException {
this.filename = filename;
this.exec = exec;
zk = new ZooKeeper(hostPort, 3000, this);//自己就是一个watcher
dm = new DataMonitor(zk, znode, null, this);
}
/**
* @param args
*/
public static void main(String[] args) {
// if (args.length < 4) {
// System.err
// .println("USAGE: Executor hostPort znode filename program [args ...]");
// System.exit(2);
// }
String hostPort = "";
String znode = "/root/child1";//args[1];
String filename = "learnzookeeperFile";
String exec[] = new String[200 - 3];
String[] args1 = {
"192.168.*。*",
"/root/child1",
"learnzookeeperFile"
};
//System.arraycopy(args, 3, exec, 0, exec.length);//需要了解一下字符串数组是怎么一回事。
try {
new Executor(hostPort, znode, filename, exec).run();
} catch (Exception e) {
e.printStackTrace();
}
}
/***************************************************************************
* We do process any events ourselves, we just need to forward them on.
*
* @see org.apache.zookeeper.Watcher#process(org.apache.zookeeper.proto.WatcherEvent)
*/
public void process(WatchedEvent event) {
dm.process(event);
}
public void run() {
try {
synchronized (this) {
int num = 0;
while (!dm.dead) {
//为什么仅仅执行了一次。
System.out.println("Executor::run times: " + num++);
wait();//这句话的含义
}
}
} catch (InterruptedException e) {
}
}
public void closing(int rc) {
synchronized (this) {
notifyAll();
}
}
static class StreamWriter extends Thread {
OutputStream os;
InputStream is;
StreamWriter(InputStream is, OutputStream os) {
this.is = is;
this.os = os;
start();
}
public void run() {
byte b[] = new byte[80];
int rc;
try {
while ((rc = is.read(b)) > 0) {
os.write(b, 0, rc);
}
} catch (IOException e) {
}
}
}
public void exists(byte[] data) {
System.out.println("Executor::exist start");
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 (Exception e) {
e.printStackTrace();
}
}
}
}
<pre name="code" class="java">package check;
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
// 后续需要打开,
System.out.println("DataMoitor::constor");
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) {
System.out.println("DataMonitor process start.");
String path = event.getPath();
System.out.println(path);
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);
}
}
//这个是系统内部的调用机制, 第一次是因为eixits调用的,第二次是在哪里调用呢?
public void processResult(int rc, String path, Object ctx, Stat stat) {
System.out.println("DataMonitor::processResult>>>start");
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;
}
}
}
package check;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
//
//import org.apache.commons.logging.Log;
//import org.apache.commons.logging.LogFactory;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.Watcher.Event.KeeperState;
public class absZookeeper implements Watcher{
private static int sessionTime = 3000;
protected ZooKeeper zookeeper;
protected CountDownLatch countDownLatch=new CountDownLatch(1);
public void connect(String con){
try {
zookeeper = new ZooKeeper(con, sessionTime, this);
countDownLatch.await();//为什么
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void process(WatchedEvent event) {
if(event.getState()==KeeperState.SyncConnected){
countDownLatch.countDown();
}
}
public void close(){
try {
zookeeper.close();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}<pre name="code" class="java">package check;
import java.util.List;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs.Ids;
public class zookeeperCheckImpl extends absZookeeper{
public void create(String path, byte[] data){
try {
this.zookeeper.create(path, data, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
} catch (KeeperException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void getChild(String path){
try {
List<String> childList = this.zookeeper.getChildren(path,false);
if(childList.isEmpty()){
System.out.println("no node in the path");
}
for(String ele : childList){
System.out.println("the node is " + ele);
}
} catch (KeeperException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void modifyData(String path, String valueModified){
//修改相关内容
//ok
try {
this.zookeeper.setData(path, valueModified.getBytes(), this.zookeeper.exists(path, true).getVersion());
} catch (KeeperException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void deleteNode(String path){
try {
this.zookeeper.delete(path, this.zookeeper.exists(path, true).getVersion());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (KeeperException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String args[]){
//
//create node.
//加入显示节点的
zookeeperCheckImpl checkSample = new zookeeperCheckImpl();
checkSample.connect("192.168.130.174");
//checkSample.getChild("/root");
byte[] data = new byte[]{'a', 'b', 'c'};//byte 的装箱对象是什么呢?
//checkSample.create("root/child1", data);
checkSample.create("/root", data);
String child1 = "child1";
checkSample.create("/root/child1", child1.getBytes());
String child2 = "child2";
checkSample.create("/root/child2", child2.getBytes());
String child3 = "child3";
checkSample.create("/root/child3", child3.getBytes());
checkSample.getChild("/root");
checkSample.modifyData("/root/child1", "modified1");
//这个看需要改成可以配置的
//checkSample.deleteNode("/root/child1");
//checkSample.deleteNode("/root/child2");
//checkSample.deleteNode("/root/child3");
//checkSample.deleteNode("/root");
checkSample.close();
}
}