[ZooKeeper]一个简单的Java示例(synchronous version)

原创 2016年05月31日 18:18:30
package felix.zookeeper.examples.simple;
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.ZooKeeper;

/**
 * A simple example program to use DataMonitor to start and
 * stop executables based on a znode. The program watches the
 * specified znode and saves the data that corresponds to the
 * znode in the filesystem. It also starts the specified program
 * with the specified arguments when the znode exists and kills
 * the program if the znode goes away.
 */
public class Executor
    implements Runnable, DataMonitor.DataMonitorListener
{
    String znode;

    DataMonitor dm;

    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;
        dm = new DataMonitor(hostPort, 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 = args[0];
        String znode = args[1];
        String filename = args[2];
        String exec[] = new String[args.length - 3];
        System.arraycopy(args, 3, exec, 0, exec.length);
        try {
            new Executor(hostPort, znode, filename, exec).run();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public void run() {
        try {
            synchronized (this) {
                while (!dm.dead) {
                    wait();
                }
            }
        } catch (InterruptedException e) {
        }
    }

    @Override
    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) {
            }

        }
    }

    @Override
    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();
            }
        }
    }
}

package felix.zookeeper.examples.simple;
import java.io.IOException;
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.KeeperException.Code;
import org.apache.zookeeper.data.Stat;

/**
 * A simple class that monitors the data and existence of a ZooKeeper
 * node. It uses asynchronous ZooKeeper APIs.
 */
public class DataMonitor implements Watcher {

    ZooKeeper zk;

    String znode;

    Watcher chainedWatcher;

    boolean dead;

    DataMonitorListener listener;

    byte prevData[];

    public DataMonitor(String hostPort, String znode, Watcher chainedWatcher,
            DataMonitorListener listener) throws IOException {
        this.zk = new ZooKeeper(hostPort, 3000, this);
        this.znode = znode;
        this.chainedWatcher = chainedWatcher;
        this.listener = listener;
        
        tryGetNodeData();
        
    }

	private void tryGetNodeData() {
		// Get things started by checking if the node exists.        
        while (!Thread.interrupted()) {
        	try {
    			Stat stat = zk.exists(znode, true);
    			
    			byte b[] = null;
    	        if (stat != null) {
    	            try {
    	                b = zk.getData(znode, false, null);
    	            } catch (KeeperException e) {
    	                /*
    	                 *  We don't need to worry about recovering now. The watch 
    	                 *  callback will kick off any exception handling
    	                 */
    	                e.printStackTrace();
    	            }
    	        }
    	        
    	        if ((b == null && b != prevData)
    	                || (b != null && !Arrays.equals(prevData, b))) {
    	            listener.exists(b);
    	            prevData = b;
    	        }
    	        break;
    	        
    		} catch (KeeperException e) {
    			if (e.code() == Code.NOAUTH || e.code() == Code.SESSIONEXPIRED) {
    				dead = true;
    				listener.closing(e.code().intValue());
    			} else {
    				// Try again!
    				continue;
    			}
    		} catch (InterruptedException e) {
    			break;
    		}
        	break;
        }
	}

    @Override
	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(Code.SESSIONEXPIRED.intValue());
                break;
			default:
				break;
            }
        } else {
            if (path != null && path.equals(znode)) {
            	tryGetNodeData();
            }
        }
        if (chainedWatcher != null) {
            chainedWatcher.process(event);
        }
	}

    /**
     * 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);
    }
}

相关文章推荐

dubbo+zookeeper简单示例.rar

  • 2017年02月17日 17:58
  • 30KB
  • 下载

Java Socket编程,一个完整的简单通信示例

第一步 充分理解Socket    1.什么是socket    所谓socket通常也称作"套接字",用于描述IP地址和端口,是一个通信链的句柄。应用程序通常通过"套接字"向网络发...

一个简单的Java EE&Docker示例

【编者的话】学习Docker的最好办法就是迅速在工作中应用它,本文作者使用Docker部署了一个Java EE应用,非常简单和方便。需要注意的是,由于作者写作时本地网络有问题,所以Dockerfile...

从一个简单的Java单例示例谈谈并发

一个简单的单例示例 单例模式可能是大家经常接触和使用的一个设计模式,你可能会这么写 public class UnsafeLazyInitiallization { private ...

由一个简单示例 引出java继承中父子类成员变量共享问题 以及super的使用

输出结果为 12 12 13 10 虚拟机执行步骤: 1:虚拟机加载测试类,提取类型信息到方法区。 2:通过保存在方法区的字节码,虚拟机开始执行main方法,main方法入栈。 3:执行m...

java播放声音类和一个简单示例

java播放声音类和一个简单示例 播放声音的类 复制代码 代码如下:  import java.io.File; import java.io.IOException; ...

JAVA套接字(Socket)101七天系列—第四天【一个简单示例】

一个简单示例  1. 背景 我们将在本部分讨论的示例将阐明在 Java 代码中如何使用 Socket 和 ServerSocket。客户机用Socket 连接到服务器。服务器用 Server...

一个简单的Java单例示例谈谈并发

一个简单的单例示例 单例模式可能是大家经常接触和使用的一个设计模式,你可能会这么写 public class UnsafeLazyInitiallization { private ...
  • hj7jay
  • hj7jay
  • 2016年05月11日 10:31
  • 3007

Java:一个简单的死锁示例

对于一个多线程程序,如果它的多个线程要使用同一部分资源,我们就可以使用某种加锁机制,比如sycrhronized方法,来防止多个线程同时使用这个资源。但使用加锁机制可能会导致死锁现象:当一个线程在执行...
  • tbx709
  • tbx709
  • 2017年04月16日 10:39
  • 111
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:[ZooKeeper]一个简单的Java示例(synchronous version)
举报原因:
原因补充:

(最多只允许输入30个字)