Search in sources :

Example 31 with PathChildrenCacheEvent

use of org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent in project np by liuhouer.

the class CuratorOperator method main.

public static void main(String[] args) throws Exception {
    // 实例化
    CuratorOperator cto = new CuratorOperator();
    boolean isZkCuratorStarted = cto.client.isStarted();
    System.out.println("当前客户的状态:" + (isZkCuratorStarted ? "连接中" : "已关闭"));
    // 创建节点
    String nodePath = "/super/imooc";
    // byte[] data = "superme".getBytes();
    // cto.client.create().creatingParentsIfNeeded()
    // .withMode(CreateMode.PERSISTENT)
    // .withACL(Ids.OPEN_ACL_UNSAFE)
    // .forPath(nodePath, data);
    // 
    // 更新节点数据
    // byte[] newData = "batman".getBytes();
    // cto.client.setData().withVersion(0).forPath(nodePath, newData);
    // 删除节点
    // cto.client.delete()
    // .guaranteed()					// 如果删除失败,那么在后端还是继续会删除,直到成功
    // .deletingChildrenIfNeeded()	// 如果有子节点,就删除
    // .withVersion(0)
    // .forPath(nodePath);
    // 读取节点数据
    // Stat stat = new Stat();
    // byte[] data = cto.client.getData().storingStatIn(stat).forPath(nodePath);
    // System.out.println("节点" + nodePath + "的数据为: " + new String(data));
    // System.out.println("该节点的版本号为: " + stat.getVersion());
    // 查询子节点
    // List<String> childNodes = cto.client.getChildren()
    // .forPath(nodePath);
    // System.out.println("开始打印子节点:");
    // for (String s : childNodes) {
    // System.out.println(s);
    // }
    // 判断节点是否存在,如果不存在则为空
    // Stat statExist = cto.client.checkExists().forPath(nodePath + "/abc");
    // System.out.println(statExist);
    // watcher 事件  当使用usingWatcher的时候,监听只会触发一次,监听完毕后就销毁
    // cto.client.getData().usingWatcher(new MyCuratorWatcher()).forPath(nodePath);
    // cto.client.getData().usingWatcher(new MyWatcher()).forPath(nodePath);
    // 为节点添加watcher
    // NodeCache: 监听数据节点的变更,会触发事件
    // final NodeCache nodeCache = new NodeCache(cto.client, nodePath);
    // // buildInitial : 初始化的时候获取node的值并且缓存
    // nodeCache.start(true);
    // if (nodeCache.getCurrentData() != null) {
    // System.out.println("节点初始化数据为:" + new String(nodeCache.getCurrentData().getData()));
    // } else {
    // System.out.println("节点初始化数据为空...");
    // }
    // nodeCache.getListenable().addListener(new NodeCacheListener() {
    // public void nodeChanged() throws Exception {
    // if (nodeCache.getCurrentData() == null) {
    // System.out.println("空");
    // return;
    // }
    // String data = new String(nodeCache.getCurrentData().getData());
    // System.out.println("节点路径:" + nodeCache.getCurrentData().getPath() + "数据:" + data);
    // }
    // });
    // 为子节点添加watcher
    // PathChildrenCache: 监听数据节点的增删改,会触发事件
    String childNodePathCache = nodePath;
    // cacheData: 设置缓存节点的数据状态
    final PathChildrenCache childrenCache = new PathChildrenCache(cto.client, childNodePathCache, true);
    /**
     * StartMode: 初始化方式
     * POST_INITIALIZED_EVENT:异步初始化,初始化之后会触发事件
     * NORMAL:异步初始化
     * BUILD_INITIAL_CACHE:同步初始化
     */
    childrenCache.start(StartMode.POST_INITIALIZED_EVENT);
    List<ChildData> childDataList = childrenCache.getCurrentData();
    System.out.println("当前数据节点的子节点数据列表:");
    for (ChildData cd : childDataList) {
        String childData = new String(cd.getData());
        System.out.println(childData);
    }
    childrenCache.getListenable().addListener(new PathChildrenCacheListener() {

        public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
            if (event.getType().equals(PathChildrenCacheEvent.Type.INITIALIZED)) {
                System.out.println("子节点初始化ok...");
            } else if (event.getType().equals(PathChildrenCacheEvent.Type.CHILD_ADDED)) {
                // 监听某个具体的路径 节点
                String path = event.getData().getPath();
                if (path.equals(ADD_PATH)) {
                    System.out.println("添加子节点:" + event.getData().getPath());
                    System.out.println("子节点数据:" + new String(event.getData().getData()));
                } else if (path.equals("/super/imooc/e")) {
                    System.out.println("添加不正确...");
                }
            } else if (event.getType().equals(PathChildrenCacheEvent.Type.CHILD_REMOVED)) {
                System.out.println("删除子节点:" + event.getData().getPath());
            } else if (event.getType().equals(PathChildrenCacheEvent.Type.CHILD_UPDATED)) {
                System.out.println("修改子节点路径:" + event.getData().getPath());
                System.out.println("修改子节点数据:" + new String(event.getData().getData()));
            }
        }
    });
    Thread.sleep(10000000);
    cto.closeZKClient();
    boolean isZkCuratorStarted2 = cto.client.isStarted();
    System.out.println("当前客户的状态:" + (isZkCuratorStarted2 ? "连接中" : "已关闭"));
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) PathChildrenCacheListener(org.apache.curator.framework.recipes.cache.PathChildrenCacheListener) PathChildrenCacheEvent(org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent) PathChildrenCache(org.apache.curator.framework.recipes.cache.PathChildrenCache) ChildData(org.apache.curator.framework.recipes.cache.ChildData)

Example 32 with PathChildrenCacheEvent

use of org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent in project np by liuhouer.

the class Client3 method main.

public static void main(String[] args) throws Exception {
    Client3 cto = new Client3();
    System.out.println("client3 启动成功...");
    final PathChildrenCache childrenCache = new PathChildrenCache(cto.client, CONFIG_NODE_PATH, true);
    childrenCache.start(StartMode.BUILD_INITIAL_CACHE);
    // 添加监听事件
    childrenCache.getListenable().addListener(new PathChildrenCacheListener() {

        public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
            // 监听节点变化
            if (event.getType().equals(PathChildrenCacheEvent.Type.CHILD_UPDATED)) {
                String configNodePath = event.getData().getPath();
                if (configNodePath.equals(CONFIG_NODE_PATH + SUB_PATH)) {
                    System.out.println("监听到配置发生变化,节点路径为:" + configNodePath);
                    // 读取节点数据
                    String jsonConfig = new String(event.getData().getData());
                    System.out.println("节点" + CONFIG_NODE_PATH + "的数据为: " + jsonConfig);
                    // 从json转换配置
                    RedisConfig redisConfig = null;
                    if (StringUtils.isNotBlank(jsonConfig)) {
                        redisConfig = (RedisConfig) JsonUtil.json2object(jsonConfig, RedisConfig.class);
                    }
                    // 配置不为空则进行相应操作
                    if (redisConfig != null) {
                        String type = redisConfig.getType();
                        String url = redisConfig.getUrl();
                        String remark = redisConfig.getRemark();
                        // 判断事件
                        if (type.equals("add")) {
                            System.out.println("监听到新增的配置,准备下载...");
                            // ... 连接ftp服务器,根据url找到相应的配置
                            Thread.sleep(500);
                            System.out.println("开始下载新的配置文件,下载路径为<" + url + ">");
                            // ... 下载配置到你指定的目录
                            Thread.sleep(1000);
                            System.out.println("下载成功,已经添加到项目中");
                        // ... 拷贝文件到项目目录
                        } else if (type.equals("update")) {
                            System.out.println("监听到更新的配置,准备下载...");
                            // ... 连接ftp服务器,根据url找到相应的配置
                            Thread.sleep(500);
                            System.out.println("开始下载配置文件,下载路径为<" + url + ">");
                            // ... 下载配置到你指定的目录
                            Thread.sleep(1000);
                            System.out.println("下载成功...");
                            System.out.println("删除项目中原配置文件...");
                            Thread.sleep(100);
                            // ... 删除原文件
                            System.out.println("拷贝配置文件到项目目录...");
                        // ... 拷贝文件到项目目录
                        } else if (type.equals("delete")) {
                            System.out.println("监听到需要删除配置");
                            System.out.println("删除项目中原配置文件...");
                        }
                    // TODO 视情况统一重启服务
                    }
                }
            }
        }
    });
    countDown.await();
    cto.closeZKClient();
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) PathChildrenCacheListener(org.apache.curator.framework.recipes.cache.PathChildrenCacheListener) PathChildrenCacheEvent(org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent) PathChildrenCache(org.apache.curator.framework.recipes.cache.PathChildrenCache) RedisConfig(cn.northpark.zookeeper.RedisConfig)

Example 33 with PathChildrenCacheEvent

use of org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent in project JHodgepodge by werwolfGu.

the class PathChildrenCacheZkClientWatcher method addListener.

public void addListener() throws Exception {
    PathChildrenCacheListener listener = new PathChildrenCacheListener() {

        @Override
        public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
            switch(event.getType()) {
                case CHILD_ADDED:
                    {
                        zkChildrenPathAdded(client, event);
                        break;
                    }
                case CHILD_UPDATED:
                    {
                        zkChildrenPathUpdated(client, event);
                        break;
                    }
                case CHILD_REMOVED:
                    {
                        zkChildrenPathDeleted(client, event);
                        break;
                    }
            }
        }
    };
    cache.getListenable().addListener(listener);
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) PathChildrenCacheListener(org.apache.curator.framework.recipes.cache.PathChildrenCacheListener) PathChildrenCacheEvent(org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent)

Example 34 with PathChildrenCacheEvent

use of org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent in project BRFS by zhangnianli.

the class FileNodeDistributor method serviceAdded.

@Override
public void serviceAdded(Service service) {
    LOG.info("Service added#######{}", service.getServiceId());
    serviceTimeTable.put(service.getServiceGroup(), service.getServiceId(), service.getRegisterTime());
    if (!childWatchers.containsKey(service.getServiceId())) {
        try {
            PathChildrenCache childWatcher = new PathChildrenCache(client, ZkFileCoordinatorPaths.buildServiceSinkPath(service), false);
            childWatcher.getListenable().addListener(new PathChildrenCacheListener() {

                @Override
                public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                    LOG.info("happen event !!!");
                    executor.submit(new Runnable() {

                        @Override
                        public void run() {
                            dispatchWildFileNode();
                        }
                    });
                }
            });
            childWatcher.start();
            childWatchers.put(service.getServiceId(), childWatcher);
        } catch (Exception e) {
            LOG.error("create path child cache error for {}", service, e);
        }
    }
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) PathChildrenCacheListener(org.apache.curator.framework.recipes.cache.PathChildrenCacheListener) PathChildrenCacheEvent(org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent) PathChildrenCache(org.apache.curator.framework.recipes.cache.PathChildrenCache) NoNodeException(org.apache.zookeeper.KeeperException.NoNodeException)

Example 35 with PathChildrenCacheEvent

use of org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent in project BRFS by zhangnianli.

the class CacheExample method main.

public static void main(String[] args) throws Exception {
    CuratorClient client = CuratorClient.getClientInstance("192.168.101.86:2181");
    final Set<String> set = new HashSet<String>();
    PathChildrenCache cache = new PathChildrenCache(client.getInnerClient(), PATH, true);
    cache.start();
    PathChildrenCacheListener listener1 = new PathChildrenCacheListener() {

        @Override
        public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
            switch(event.getType()) {
                case CHILD_ADDED:
                    {
                        System.out.println("1Node added: " + ZKPaths.getNodeFromPath(event.getData().getPath()));
                        System.out.println("1Node added: " + event.getData().getPath());
                        break;
                    }
                case CHILD_UPDATED:
                    {
                        System.out.println("1Node changed: " + ZKPaths.getNodeFromPath(event.getData().getPath()));
                        System.out.println("1Node changed: " + new String(event.getData().getData()));
                        break;
                    }
                case CHILD_REMOVED:
                    {
                        System.out.println("1Node removed: " + ZKPaths.getNodeFromPath(event.getData().getPath()));
                        break;
                    }
                default:
                    break;
            }
        }
    };
    // PathChildrenCacheListener listener2 = new PathChildrenCacheListener() {
    // 
    // @Override
    // public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
    // switch (event.getType()) {
    // case CHILD_ADDED: {
    // System.out.println("2Node added: " + ZKPaths.getNodeFromPath(event.getData().getPath()));
    // System.out.println("2Node added: " + event.getData().getPath());
    // break;
    // }
    // case CHILD_UPDATED: {
    // System.out.println("2Node changed: " + ZKPaths.getNodeFromPath(event.getData().getPath()));
    // break;
    // }
    // case CHILD_REMOVED: {
    // System.out.println("2Node removed: " + ZKPaths.getNodeFromPath(event.getData().getPath()));
    // break;
    // }
    // default:
    // break;
    // }
    // }
    // };
    ExecutorService services = Executors.newFixedThreadPool(5);
    cache.getListenable().addListener(listener1, services);
    // cache.getListenable().addListener(listener2,services);
    // cache.getListenable().addListener(listener);
    Thread.sleep(Long.MAX_VALUE);
    cache.close();
    client.close();
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) PathChildrenCacheListener(org.apache.curator.framework.recipes.cache.PathChildrenCacheListener) PathChildrenCacheEvent(org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent) PathChildrenCache(org.apache.curator.framework.recipes.cache.PathChildrenCache) CuratorClient(com.bonree.brfs.common.zookeeper.curator.CuratorClient) ExecutorService(java.util.concurrent.ExecutorService) HashSet(java.util.HashSet)

Aggregations

PathChildrenCacheEvent (org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent)65 CuratorFramework (org.apache.curator.framework.CuratorFramework)55 PathChildrenCacheListener (org.apache.curator.framework.recipes.cache.PathChildrenCacheListener)49 PathChildrenCache (org.apache.curator.framework.recipes.cache.PathChildrenCache)34 ChildData (org.apache.curator.framework.recipes.cache.ChildData)20 IOException (java.io.IOException)15 KeeperException (org.apache.zookeeper.KeeperException)11 CountDownLatch (java.util.concurrent.CountDownLatch)10 Test (org.junit.Test)10 DataSegment (org.apache.druid.timeline.DataSegment)5 ZKPaths (org.apache.curator.utils.ZKPaths)4 RedisConfig (cn.northpark.zookeeper.RedisConfig)3 SofaRpcRuntimeException (com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException)3 ServiceInstance (com.baidu.brpc.client.channel.ServiceInstance)3 RpcException (com.baidu.brpc.exceptions.RpcException)3 DataSegment (io.druid.timeline.DataSegment)3 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3 Releasable (com.ctrip.xpipe.api.lifecycle.Releasable)2