curator 监听用法范例

模块介绍:

1.curator连接创建、管理

2.watcher 基类,预定义实现了各事件下应实现的方法(空方法),用于添加通用的监听动作;特定节点的的watcher可以集成该基类,做到添加监听的解耦;

3.监听添加工具类

初始化curator连接

package com.von.zookeeper;

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

public class ZookeeoerConnectManager {

    private static CuratorFramework client;

    // private Cura
    public static void init() {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        client = CuratorFrameworkFactory.newClient("127.0.0.1:8081", 2000, 8000, retryPolicy);
        client = CuratorFrameworkFactory.builder().connectString("127.0.0.1:8081").connectionTimeoutMs(2000)
                .connectionTimeoutMs(5000).retryPolicy(retryPolicy).build();
    }

    public static CuratorFramework getConnect() {
        return client;
    }
    
    public static void close() {
        client.getZookeeperClient().close();
    }

}

watcher 基类:

package com.von.zookeeper;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.ChildData;

public class Watcher {
    /**
     * Factory methods for creating framework-style clients 节点uodated时触发
     */
    public void onNodeUpdated(CuratorFramework client, ChildData childData) throws Exception {
    }

    public void onTreeNodeUpdated(CuratorFramework client, ChildData childData) throws Exception {
    }

    public void onTreeNodeRemove(CuratorFramework client, ChildData childData) throws Exception {
    }

    public void onTreeNodeAdd(CuratorFramework client, ChildData childData) throws Exception {
    }

    public void onChildAdd(CuratorFramework client, ChildData childData) throws Exception {
    }

    public void onChildRemove(CuratorFramework client, ChildData childData) throws Exception {
    }

    public void onChildUpdate(CuratorFramework client, ChildData childData) throws Exception {
    }
}

监听添加工具类

package com.von.zookeeper;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.framework.recipes.cache.TreeCache;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import org.apache.curator.framework.recipes.cache.TreeCacheListener;
import org.apache.curator.framework.recipes.cache.PathChildrenCache.StartMode;

public class WatcherUtils {
    public static PathChildrenCache addPathChildrenWatcher(CuratorFramework client, String path, final Watcher handler)
            throws Exception {
        final PathChildrenCache pathChildrenCache = new PathChildrenCache(client, path, true);
        pathChildrenCache.start(StartMode.BUILD_INITIAL_CACHE);
        pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {

            public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                switch (event.getType()) {
                    case CHILD_ADDED:
                        handler.onChildAdd(client, event.getData());
                        break;
                    case CHILD_REMOVED:
                        handler.onChildRemove(client, event.getData());
                        break;
                    case CHILD_UPDATED:
                        handler.onNodeUpdated(client, event.getData());
                        break;
                    default:
                        break;
                }
            }
        });
        return pathChildrenCache;
    }

    // NodeCache nodeCache
    public static NodeCache addNodeWatcher(final CuratorFramework client, final String path, final Watcher handler)
            throws Exception {
        final NodeCache nodeCache = new NodeCache(client, path, true);

        nodeCache.start();
        nodeCache.getListenable().addListener(new NodeCacheListener() {
            public void nodeChanged() throws Exception {
                ChildData childData = nodeCache.getCurrentData();
//                byte[] data = client.getData().forPath(path);
                handler.onNodeUpdated(client, childData);
            }
        });
        return nodeCache;
    }

    // TreeCache
    public static TreeCache addTreeWatcher(CuratorFramework client, String path, final Watcher handler)
            throws Exception {
        final TreeCache treeCache = new TreeCache(client, path);
        treeCache.start();
        treeCache.getListenable().addListener(new TreeCacheListener() {

            public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception {
                switch (event.getType()) {
                    case NODE_ADDED:
                        handler.onTreeNodeAdd(client, event.getData());
                        break;
                    case NODE_REMOVED:
                        handler.onTreeNodeRemove(client, event.getData());
                        break;
                    case NODE_UPDATED:
                        handler.onTreeNodeUpdated(client, event.getData());
                        break;
                    default:
                        break;
                }

            }
        });
        return treeCache;
    }
}

 

测试工具类(待完善):

package com.von.zookeeper;

import java.io.Closeable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

public class CuratorTools {
    
    static ExecutorService pool = Executors.newCachedThreadPool();

    public static void creatTempNode(String path, String data) throws Exception {
        ZookeeoerConnectManager.getConnect().create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL)
                .forPath(path, data == null ? new byte[0] : data.getBytes("utf-8"));
    }

    public static void creatNode(String path, String data) throws Exception {
        Stat stat = ZookeeoerConnectManager.getConnect().checkExists().forPath(path);
        if (null == stat) {
            ZookeeoerConnectManager.getConnect().create().creatingParentsIfNeeded().forPath(path,
                    data == null ? new byte[0] : data.getBytes("utf-8"));
        }
    }
    
    public static Closeable watcherChildren(String path ,Watcher watcher) throws Exception
    {
        return WatcherUtils.addPathChildrenWatcher(ZookeeoerConnectManager.getConnect(), path, watcher);
    }

}

 

posted on 2017-08-07 22:07  Dr.Von  阅读(260)  评论(0)    收藏  举报

导航