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. Linux C 重定向简单范例

    //前言:我们知道printf()会将信息输出到stdout流,然后展示到屏幕上. //那么我们所实现的简单的重定向就可以将stdout指向一个文件,然后读写,这样就达到了重定向的目的. //code ...

  2. c++之选择排序和冒泡排序实现

     1.冒泡排序 冒泡排序就是通过对比前一个和后一个数的大小,按照规则进行顺序的调换.每一轮对比之后最大或者最小值都会浮到最上面或者沉到最低下. 如:对这一数组进行冒泡排序:int a[5]{34,12 ...

  3. js 移动端获取当前用户的经纬度

    一.HTML5 geolocation的属性 if(navigator.geolocation){ navigator.geolocation.getCurrentPosition(onSuccess ...

  4. 认识python正则模块re

    python正则模块re python中re中内置匹配.搜索.替换方法见博客---python附录-re.py模块源码(含re官方文档链接) 正则的应用是处理一些字符串,phthon的博文python ...

  5. [iOS]使用Windows Azure來做iOS的推播通知 (转帖)

    這一篇我們用Windows Azure 的Mobile Service 來實作iOS的推播通知,底下我們分成三個階段來探討如何實作推播通知的服務: 第一階段: 開啓你的Windows Aure服務   ...

  6. 【MPI】执行mpiexec出错

    运行mpiexec提示mpiexec_mic: cannot connect to local mpd (/tmp/mpd2.console_jzhang); possible causes: 1. ...

  7. 【Kafka】Broker之Server.properties的重要参数说明

    名称 描述 类型 默认值 有效值区间 重要程度 zookeeper.connect zk地址 string 高 advertised.host.name 过时的:只有当advertised.liste ...

  8. 002javascript变量&数据类型

    •变量 –JavaScript 是一种弱类型的脚本语言 –var c = 3:即变量的声明(变量使用之前必须加var声明,编程规范) –变量的命名规则! •1.变量命名必须以字母或是下标符号”_”或者 ...

  9. Go语言学习笔记三: 常量

    Go语言学习笔记三: 常量 定义常量 常量就是在声明后不能再修改的量. const x int = 100 const y string = "abc" const z = &qu ...

  10. OpenLdap与BerkeleyDB安装过程

    前段时间在看LDAP方面的东西,最近重装了Ubuntu之后开始在自己的机器上装一个OpenLDAP. 装的过程中还遇到不少问题,不过通过Google同学的帮忙,全部得到解决.下面装安装过程记录如下: ...