0. 原生 ZOOKEEPER JAVA API  http://www.cnblogs.com/rocky-fang/p/9030438.html

1. 概述

Curator采用cache封装对事件的监听,包括监听节点、子节点。主要有:

NodeCache、PathChildrenCache、TreeCache

2. 例子

2.1 NodeCache

监听节点本身的变化,当节点的状态发生变更后,回调NodeCacheListener

代码

package com.rocky.learn.curator;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
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.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper; import javax.xml.ws.soap.Addressing;
import java.io.IOException;
import java.util.concurrent.CountDownLatch; /**
* @Author: rocky
* @Date: Created in 2018/5/14.
*/
public class NodeCacheTest {
private static final CountDownLatch countDownLatch = new CountDownLatch(1);
private static final String ADDRESS = "10.0.40.10:2181";
private static final String PREFIX_SYNC = "/mytest-curator";
private static final String NAMESPACE = "mybase";
private static CuratorFramework client;
private static NodeCache nodeCache;
static {
// client = CuratorFrameworkFactory.newClient(ADDRESS, 5000, 5000,
// new ExponentialBackoffRetry(1000, 3));
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
client = CuratorFrameworkFactory.builder()
.connectString(ADDRESS)
.sessionTimeoutMs(5000)
.connectionTimeoutMs(5000)
.retryPolicy(retryPolicy)
.namespace(NAMESPACE)
.build();
client.start();
}
private static void initCache() throws Exception {
client.create().forPath(PREFIX_SYNC);
client.setData().forPath(PREFIX_SYNC,"hello curator..".getBytes());
nodeCache = new NodeCache(client, PREFIX_SYNC);
nodeCache.start(true);
startCache(nodeCache);
} private static void startCache(final NodeCache nodeCache) throws Exception {
ChildData currentData = nodeCache.getCurrentData();
System.out.println("1111:" + new String(currentData.getData()));
nodeCache.getListenable().addListener(new NodeCacheListener() {
public void nodeChanged() throws Exception {
System.out.println("data change..." + new String(nodeCache.getCurrentData().getData()));
countDownLatch.countDown();
}
});
Thread.sleep(2000);
if(client.checkExists().forPath(PREFIX_SYNC) != null){
System.out.println("设置新内容。。。。");
client.setData().forPath(PREFIX_SYNC, "2222".getBytes());
}
} public static void main(String[] args) throws Exception {
initCache();
countDownLatch.await();
}
}

控制台

2.2. PathChildrenCache

主要用来监听子节点,并且不会对二级节点进行监听

代码

package com.rocky.learn.curator;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.ChildData;
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.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.data.Stat; import java.util.concurrent.CountDownLatch; /**
* @Author: rocky
* @Date: Created in 2018/5/15.
*/
public class PathCacheTest {
private static final String PATH = "/mycache/test7";
private static final String ADDRESS = "10.0.40.10:2181";
private static final String BASE = "mybase";
private static PathChildrenCache pathChildrenCache;
private static CuratorFramework client;
private static CountDownLatch countDownLatch = new CountDownLatch(1);
private static CountDownLatch countDownLatch2 = new CountDownLatch(5);
static {
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
client = CuratorFrameworkFactory.builder()
.connectString(ADDRESS)
.sessionTimeoutMs(5000)
.connectionTimeoutMs(5000)
.retryPolicy(retryPolicy)
// .namespace(BASE)
.build();
client.start();
} public static void main(String[] args) throws Exception {
startCache();
countDownLatch.await();
} private static void startCache() throws Exception {
pathChildrenCache = new PathChildrenCache(client, PATH, true);
pathChildrenCache.start();
for (int i = 1; i < 6; i++) {
String newPath = PATH + "/child_" + i;
String childNodeName = "child_" + i;
client.create().creatingParentsIfNeeded().forPath(newPath, childNodeName.getBytes());
countDownLatch2.countDown();
}
countDownLatch2.await();
addListener(pathChildrenCache);
for(final ChildData childData : pathChildrenCache.getCurrentData()){
System.out.println("输出: child path :" + childData.getPath() +
", child data: " + new String(childData.getData()));
}
Thread.sleep(2000);
System.out.println("父节点设值......start");//不会有事件监听返回
client.setData().forPath(PATH, "11111".getBytes());
System.out.println("父节点设值......end");
System.out.println("子节点 del....start");
client.delete().forPath(PATH + "/child_1");
System.out.println("子节点 del....end");
Thread.sleep(2000);
for(int j=1; j<3; j++){
String newPath = PATH + "/child_2/" + j;
String nodeName = "child_2_"+ j;
client.create().forPath(newPath, nodeName.getBytes());
}
addListener(pathChildrenCache);
System.out.println("二级节点 del...start");//不会有事件监听返回
client.delete().forPath(PATH + "/child_2/2");
System.out.println("二级节点 del...end");
countDownLatch.countDown(); } private static void addListener(final PathChildrenCache pathChildrenCache) {
final PathChildrenCacheListener pathChildrenCacheListener = new PathChildrenCacheListener() {
public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent event) throws Exception {
System.out.println("listener child node path :" + event.getData().getPath() +
", child node data: " + new String(event.getData().getData()));
}
};
pathChildrenCache.getListenable().addListener(pathChildrenCacheListener);
} }

控制台

注意:上面输出 部分监听没有触发,应该是操作频繁,可以使用sleep间隔一下。

有多个构造函数,并支持线程池回调

    public PathChildrenCache(CuratorFramework client, String path, boolean cacheData, boolean dataIsCompressed, ThreadFactory threadFactory) {
this(client, path, cacheData, dataIsCompressed, new CloseableExecutorService(Executors.newSingleThreadExecutor(threadFactory), true));
} public PathChildrenCache(CuratorFramework client, String path, boolean cacheData, boolean dataIsCompressed, ExecutorService executorService) {
this(client, path, cacheData, dataIsCompressed, new CloseableExecutorService(executorService));
}

2.3. TreeCache

既能监听节点 也能监听子节点

代码

package com.rocky.learn.curator;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.*;
import org.apache.curator.retry.ExponentialBackoffRetry; import java.util.concurrent.CountDownLatch; /**
* @Author: rocky
* @Date: Created in 2018/5/15.
*/
public class TreeCacheTest {
private static final String PATH = "/mytreecache/test";
private static final String ADDRESS = "10.0.40.10:2181";
private static TreeCache treeCache;
private static CuratorFramework client;
private static CountDownLatch countDownLatch = new CountDownLatch(1);
static {
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
client = CuratorFrameworkFactory.builder()
.connectString(ADDRESS)
.sessionTimeoutMs(5000)
.connectionTimeoutMs(5000)
.retryPolicy(retryPolicy)
// .namespace(BASE)
.build();
client.start();
} public static void main(String[] args) throws Exception {
startCache();
countDownLatch.await();
} private static void startCache() throws Exception {
treeCache = new TreeCache(client, PATH);
treeCache.start();
addListener();
for (int i = 1; i < 4; i++) {
String newPath = PATH + "/child_" + i;
String childNodeName = "child_" + i;
client.create().creatingParentsIfNeeded().forPath(newPath, childNodeName.getBytes());
}
Thread.sleep(2000);
client.setData().forPath(PATH, "change Papa Data first time".getBytes());
Thread.sleep(2000);
if(null != client.checkExists().forPath(PATH))
client.setData().forPath(PATH + "/child_1", "change son Data first time".getBytes());
Thread.sleep(2000);
client.setData().forPath(PATH, "change Papa Data second time".getBytes());
Thread.sleep(2000);
countDownLatch.countDown(); } private static void addListener() {
treeCache.getListenable().addListener(new TreeCacheListener() {
public void childEvent(CuratorFramework curatorFramework, TreeCacheEvent treeCacheEvent) throws Exception {
System.out.println("node change...data>>" + new String(treeCacheEvent.getData().getData()));
}
});
} }

控制台

只要节点发生变化,监听事件就回执行回调,不论父节点还是子节点,且不用反复注册。

2.4 ConnectionStateListener

代码

        client.getConnectionStateListenable().addListener(new ConnectionStateListener() {
public void stateChanged(CuratorFramework curatorFramework, ConnectionState state) {
if(state == ConnectionState.CONNECTED){
System.out.println("zk connected..");
}else if(state == ConnectionState.LOST){
System.out.println("zk session lost..");
}else if(state == ConnectionState.RECONNECTED){
System.out.println("zk reconnected..");
}
}
});

ConnectionStateListener监控连接的状态,当连接状态为LOST,curator-recipes下的所有Api将会失效或者过期

2.5 close

用完后最好关闭 cache和 client(CuratorFramework)

cache.close(); client.close()

Zookeeper Curator API 使用的更多相关文章

  1. Zookeeper系列三:Zookeeper客户端的使用(Zookeeper原生API如何进行调用、ZKClient、Curator)和Zookeeper会话

    一.Zookeeper原生API如何进行调用 准备工作: 首先在新建一个maven项目ZK-Demo,然后在pom.xml里面引入zk的依赖 <dependency> <groupI ...

  2. Zookeeper 系列(五)Curator API

    Zookeeper 系列(五)Curator API 一.Curator 使用 Curator 框架中使用链式编程风格,易读性更强,使用工程方法创建连接对象使用. (1) CuratorFramewo ...

  3. zookeeper curator客户端之增删改查

    zookeeper curator客户端之增删改查 zookeeper安装:https://www.cnblogs.com/zwcry/p/10272506.html curator客户端是Apach ...

  4. (原) 2.1 Zookeeper原生API使用

    本文为原创文章,转载请注明出处,谢谢 Zookeeper原生API使用 1.jar包引入,演示版本为3.4.6,非maven项目,可以下载jar包导入到项目中 <dependency> & ...

  5. Zookeeper C API 指南四(C API 概览)(转)

    上一节<Zookeeper C API 指南三(回调函数)>重点讲了 Zookeeper C API 中各种回调函数的原型,本节将切入正题,正式讲解 Zookeeper C API.相信大 ...

  6. Zookeeper C API 指南三(回调函数)(转)

    2013-02-21 12:54 by Haippy, 9237 阅读, 0 评论, 收藏, 编辑 接上一篇<Zookeeper C API 指南二(监视(Wathes), 基本常量和结构体介绍 ...

  7. Zookeeper C API 指南一(转)

    Zookeeper 监视(Watches) 简介 Zookeeper C API 的声明和描述在 include/zookeeper.h 中可以找到,另外大部分的 Zookeeper C API 常量 ...

  8. zookeeper client API实现(python kazoo 的实现)

    这里主要分析zookeeper client API的实现方式,以python kazoo的实现代码为蓝本进行逻辑分析. 一.代码框架及介绍 API分为同步模式和异步模式.同步模式是在异步模式的基础上 ...

  9. 9. 使用ZooKeeper Java API编程

    ZooKeeper是用Java开发的,3.4.6版本的Java API文档可以在http://zookeeper.apache.org/doc/r3.4.6/api/index.html上找到. Ti ...

随机推荐

  1. ubuntu配置实验

    实验:ubuntu配置   需求: caterpillar公司管理员小李需要将公司系统由windows全部更换为ubuntu,并制定SOP(操作指导书) 环境:vmware workstation 1 ...

  2. 2016级算法期末上机-I.难题·ModricWang's Fight with DDLs III

    1126 ModricWang's Fight with DDLs III 思路 由于题目中已经说明了时间经过了正无穷,因此初始位置是不重要的,并且每条边.每个点的地位是均等的.因此到达每个点的概率就 ...

  3. Web篇之JS性能优化

    首先,性能优化分好几个方面,本章我们从js方面来优化. 1:垃圾收集 日常中的某些情况下垃圾收集器无法回收无用变量,导致的一个结果就是——内存使用率不断增高,以下为对应的情况以及处理方法. ①对象相互 ...

  4. C#常用总结《一》

    集合类常用: List<T> 泛型集合 Dictionary<key,value>  字典集合 文件读取: FileStream :对各种文件读写,字节处理更好 StreamR ...

  5. 一、OPENERP 的一个demo

    安装好OPENERP后,使用 ps -aux|grep openerp 从输出的内容可以得到OPENERP的安装信息, /usr/bin/python /usr/bin/openerp-server ...

  6. Mac下包管理平台homebrew的使用

    一.安装 参考:http://www.cnblogs.com/EasonJim/p/6287098.html 二.使用 假设我要安装node,命令如下: 安装软件 brew install node ...

  7. 【Guava】基于guava的重试组件Guava-Retryer

    一.使用场景 在日常开发中,我们经常会遇到需要调用外部服务和接口的场景.外部服务对于调用者来说一般都是不可靠的,尤其是在网络环境比较差的情况下,网络抖动很容易导致请求超时等异常情况,这时候就需要使用失 ...

  8. JVM-类加载过程(Java类的生命周期)

    什么是类加载 类的加载指的是将类的.class文件中的二进制数据读入到内存中,将其放在运行时数据区的方法区内,然后在堆区创建一个java.lang.Class对象,用来封装类在方法区内的数据结构.类的 ...

  9. 由UI刷新谈到线程安全和Android单线程模型

    1.为什么说invalidate()不能直接在线程中调用? Android提供了Invalidate方法实现界面刷新,但是Invalidate不能直接在非UI主线程中调用,因为他是违背了单线程模型:A ...

  10. js跳出循环:break 、continue 、return

    js跳出循环:break .continue .return 本文虽然讲的是js里跳出循环的方法,但是jquery其实就是在js的基础上封装而来的,所以一些js里的语法应用,在jquery里也是通用的 ...