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. 根据现有PDF模板填充信息(SpringBoot)

    根据现有PDF模板填充信息(SpringBoot+maven) 首先得有一个pdf模板,建立pdf模板需要下载工具 红色框为文本框,filename为域名.java需要根据域名赋值 pom 文件配置 ...

  2. 洛谷 P3757 [CQOI2017]老C的键盘

    题面 luogu 题解 其实就是一颗二叉树 我们假设左儿子小于根,右儿子大于根 考虑树形\(dp\) \(f[u][i]\)表示以\(u\)为根的子树,\(u\)为第\(i\)小 那么考虑子树合并 其 ...

  3. jquery中ajax使用error调试错误的方法,实例分析了Ajax的使用方法与error函数调试错误的技巧

    代码:$(document).ready(function() { jQuery("#clearCac").click(function() { jQuery.ajax({ url ...

  4. Sql语句里的递归查询 SqlServer2005和Oracle 两个版本

    以前使用Oracle,觉得它的递归查询很好用,就研究了一下SqlServer,发现它也支持在Sql里递归查询举例说明:SqlServer2005版本的Sql如下:比如一个表,有id和pId字段,id是 ...

  5. elixir中的truth和true

    在elixir中, true 就是true 或者是:true 是一个原子 atom, 在其他语言中的true,这里叫做truth, 只要你不是false,nil ,就是truth, 当然 false和 ...

  6. display:block、inline、inline-block的区别及应用案例

    A.display:block就是将元素显示为块级元素. block元素的特点是: 1.总是在新行上开始: 2.高度,行高以及顶和底边距都可控制: 3.宽度缺省是它的容器的100%,除非设定一个宽度; ...

  7. 饶军:Apache Kafka的过去,现在,和未来

    欢迎大家前往腾讯云+社区,获取更多腾讯海量技术实践干货哦~ 本文首发在云+社区,未经许可,不得转载. 大家好,我大概简单的介绍一下,我叫饶军,我是硅谷的初创公司Confluent的联合创始人之一,我们公 ...

  8. c++删除容器中的奇数

    出自 c++ primer(4th)282页,26题 题意 数组ia[]={0,1,1,2,3,5,8,13,21,55,89};把ia复制到一个list容器中.使用单个迭代器参数版本的erase() ...

  9. P2P 行业解决方案

    P2P指个人与个人之间的借贷,而P2P理财是指以公司为中介机构,把这借贷双方对接起来实现各自的借贷需求.借款方可以是无抵押贷款或是有抵押贷款.而中介一般是收取双方或单方的手续费为盈利目的或者是赚取一定 ...

  10. Python36和Python27共存的方法

    Python26和Python37环境的配置 设置环境变量 我的电脑右键属性-高级系统属性-环境变量 选择系统变量中的Path,双击打开 加入你的Python安装路径 C:\Python27;C:\P ...