项长老

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
import java.util.List;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;

public class SpiderWatcher implements Watcher {
    CuratorFramework client = null;
    List<String> list1 = null;

    public SpiderWatcher() {
        String connectString = "192.168.14.139:2181";
        int sessionTimeoutMs = 30000;
        int connectionTimeoutMs = 30000;
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(5000, 3);
        client = CuratorFrameworkFactory.newClient(connectString, sessionTimeoutMs, connectionTimeoutMs, retryPolicy);
        client.start();
        try {
            list1 = client.getChildren().usingWatcher(this).forPath("/dddd");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void process(WatchedEvent arg0) {
        try {
            List<String> list2 = client.getChildren().usingWatcher(this).forPath("/dddd");
            for (String znode : list1) {
                if (!list2.contains(znode)) {
                    System.out.println("删除");
                }
            }
            for (String znode : list2) {
                if (!list1.contains(znode)) {
                    System.out.println("新增");
                }
            }
            list1 = list2;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void stayAlive() {
        for (;;) {
        }
    }

    public static void main(String[] args) throws Exception {
        SpiderWatcher spiderWatcher = new SpiderWatcher();
        spiderWatcher.stayAlive();
    }
}

 

posted on 2016-05-05 21:51  项长老  阅读(497)  评论(0编辑  收藏  举报