[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);
    }
}

ZooKeeper Java API简单示例

ZooKeeper Java API简单示例
  • lipeng_bigdata
  • lipeng_bigdata
  • 2016年03月26日 10:24
  • 1494

ZooKeeper简单介绍(一)

这篇博文我们简单的介绍一下什么是ZooKeeper,ZooKeeper的下载安装,以及Zookeeper的整体概况,它们将作为黑暗中的探照灯指明我们前进的方向。...
  • jiuqiyuliang
  • jiuqiyuliang
  • 2016年04月29日 16:28
  • 10270

(四)、ZooKeeper Java示例

利用ZooKeeper简单的创建节点信息。项目使用的是Maven工程。工程结构如下: POM文件 ...
  • liuyuehu
  • liuyuehu
  • 2016年08月05日 12:43
  • 4403

ZooKeeper watcher和version

ZooKeeper的用途:distributed coordination;maintaining configuration information, naming, providing distr...
  • xiaobai51509660
  • xiaobai51509660
  • 2015年03月13日 11:21
  • 1289

一个简单的MVC实例

一个简单的MVC实例 利用jsp+javabean+Servlet模拟一个用户登陆,实现对数据库的增删改查。 1,创建数据库 我使用的数据库是MySql,创建一个Iuser表,具体如下   ...
  • wikiBlue
  • wikiBlue
  • 2016年04月28日 08:48
  • 886

kafka Kafka JAVA客户端代码示例

转载:http://my.oschina.net/cloudcoder/blog/299215 感谢! 介绍      http://kafka.apache.org      kafka是一种高...
  • An342647823
  • An342647823
  • 2014年12月16日 17:57
  • 1196

Java一个简单的死锁例子

内容:一个简单的死锁例子,大概的思路:两个线程A和B,两把锁X和Y,现在A先拿到锁X,然后sleep()一段时间,我们知道sleep()是不会释放锁资源的。然后如果这段时间线程B拿到锁Y,也sleep...
  • u011345136
  • u011345136
  • 2015年05月16日 20:07
  • 1784

Sqlite synchronous设置

在一次性大量插入数据库的操作 ,会导致存储缓慢。 如 5k以上的操作会 几十秒或几分钟 很多已经给出了解决方案 ,  SQLiteDatabase db = super.getDatabase...
  • zhanghw0917
  • zhanghw0917
  • 2015年11月17日 18:00
  • 7642

Zookeeper入门-Java版本HelloWorld例子

上一篇介绍了,Zookeeper的基本概念,怎么启动,怎么解决可能遇到的几个问题。本篇,根据网上代码,整理了一个例子,Zookeeper的HelloWorld。下面这个代码,还是比较简单的,核心类就是...
  • FansUnion
  • FansUnion
  • 2015年12月01日 11:18
  • 5006

zookeeper搭建以及Java连接zookeeper测试

一、zookeeper搭建 1、下载zookeeper http://www.apache.org/dist/zookeeper/ 2、在Linux下面解压   3、配置zoo...
  • ailikce
  • ailikce
  • 2016年05月19日 15:16
  • 547
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:[ZooKeeper]一个简单的Java示例(synchronous version)
举报原因:
原因补充:

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