1. 程式人生 > >zookeeper持續監聽小技巧

zookeeper持續監聽小技巧

java實現zookeeper持續監聽:

public class ZkDemo {

    //設定一個靜態變數
    public static ZooKeeper zk = null;
    public  static int times=0;

    public static void main(String[] args) throws InterruptedException, IOException, KeeperException {
        zk = new ZooKeeper("node1:2181,node3:2181,node2:2181",
                3000,
                new Watcher() {
                    public void process(WatchedEvent watchedEvent) {
                        System.out.println("watch 第" + times++ +":次 , 路徑: "+ watchedEvent.getPath()+"\t  "+watchedEvent.getState()+"\t  "+ watchedEvent.getType());

                        // 迴圈監控
                        try {

                            zk.getData(watchedEvent.getPath(), true, null);

                        } catch (KeeperException e) {

                            e.printStackTrace();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                });

        // zk.create("/tt2", "第一個".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        zk.getData("/tt", true, null);

        // 迴圈監聽不退出會話
        while (true){

        }
    }

}