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. leetcode-219-Contains Duplicate II(使用set来判断长度为k+1的闭区间中有没有重复元素)

    题目描述: Given an array of integers and an integer k, find out whether there are two distinct indices i ...

  2. 【JavaScript】__proto__和prototype的区别和联系【整理】

    var person={name:'ninja'}; person.prototype.sayName=function(){ return this.name; } Chrome运行结果: 提示找不 ...

  3. python连接,操作 InfluxDB

    准备工作 启动服务器 执行如下命令: service influxdb start 示例如下: [root@localhost ~]# service influxdb start Starting ...

  4. panda的query过滤

    pandas中可以用query函数以类SQL语言执行查询.

  5. windows下python管理右键菜单

    实现很简单,不记得什么时候写的了,贴出来希望能有所价值 """ Windows中创建右键菜单 """ import os import sy ...

  6. 认识CSS3新增选择器和样式

    前端之HTML5,CSS3(二) CSS3新增选择器和样式 CSS3新增选择器 结构伪类选择器 :first-child:选取父元素中的第一个子元素的指定选择器 :last-child:选取父元素中的 ...

  7. Tomcat *的安装和运行(绿色版和安装版都适用)

    不多说,直接上干货! 前提, Tomcat *的下载(绿色版和安装版都适用) 一.Tomcat的安装版 1.新建安装目录 2.放置安装版的tomcat 3.双击 4.点击 I agree 5.选择“F ...

  8. 学习并发包常用的接口----java.util.concurrent

    1.常用的相关的接口 Callable.(Runnable).Futrue.RunnableFuture.RunnableSheduledFuture.ScheduledFuture.Executor ...

  9. 数据库分库分表(一)常见分布式主键ID生成策略

    主键生成策略 系统唯一ID是我们在设计一个系统的时候常常会遇见的问题,下面介绍一些常见的ID生成策略. Sequence ID UUID GUID COMB Snowflake 最开始的自增ID为了实 ...

  10. leetcode2:线性表

    /********************************************** Function:input two array and find the kth value the ...