关闭

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

标签: ZooKeeper
247人阅读 评论(0) 收藏 举报
分类:
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);
    }
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:93815次
    • 积分:1767
    • 等级:
    • 排名:千里之外
    • 原创:69篇
    • 转载:98篇
    • 译文:0篇
    • 评论:18条
    文章分类
    最新评论