Zookeeper Curator API 使用
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 使用的更多相关文章
- Zookeeper系列三:Zookeeper客户端的使用(Zookeeper原生API如何进行调用、ZKClient、Curator)和Zookeeper会话
一.Zookeeper原生API如何进行调用 准备工作: 首先在新建一个maven项目ZK-Demo,然后在pom.xml里面引入zk的依赖 <dependency> <groupI ...
- Zookeeper 系列(五)Curator API
Zookeeper 系列(五)Curator API 一.Curator 使用 Curator 框架中使用链式编程风格,易读性更强,使用工程方法创建连接对象使用. (1) CuratorFramewo ...
- zookeeper curator客户端之增删改查
zookeeper curator客户端之增删改查 zookeeper安装:https://www.cnblogs.com/zwcry/p/10272506.html curator客户端是Apach ...
- (原) 2.1 Zookeeper原生API使用
本文为原创文章,转载请注明出处,谢谢 Zookeeper原生API使用 1.jar包引入,演示版本为3.4.6,非maven项目,可以下载jar包导入到项目中 <dependency> & ...
- Zookeeper C API 指南四(C API 概览)(转)
上一节<Zookeeper C API 指南三(回调函数)>重点讲了 Zookeeper C API 中各种回调函数的原型,本节将切入正题,正式讲解 Zookeeper C API.相信大 ...
- Zookeeper C API 指南三(回调函数)(转)
2013-02-21 12:54 by Haippy, 9237 阅读, 0 评论, 收藏, 编辑 接上一篇<Zookeeper C API 指南二(监视(Wathes), 基本常量和结构体介绍 ...
- Zookeeper C API 指南一(转)
Zookeeper 监视(Watches) 简介 Zookeeper C API 的声明和描述在 include/zookeeper.h 中可以找到,另外大部分的 Zookeeper C API 常量 ...
- zookeeper client API实现(python kazoo 的实现)
这里主要分析zookeeper client API的实现方式,以python kazoo的实现代码为蓝本进行逻辑分析. 一.代码框架及介绍 API分为同步模式和异步模式.同步模式是在异步模式的基础上 ...
- 9. 使用ZooKeeper Java API编程
ZooKeeper是用Java开发的,3.4.6版本的Java API文档可以在http://zookeeper.apache.org/doc/r3.4.6/api/index.html上找到. Ti ...
随机推荐
- docker 限制 容器内存 使用
转载 : https://www.cnblogs.com/sparkdev/p/8032330.html 默认情况下容器使用的资源是不受限制的.也就是可以使用主机内核调度器所允许的最大资源.但是在容器 ...
- ui7
2016.9讲义 一.课程的主要内容和目的 二.课程所用工具软件——Photoshop CS6 1. Photoshop 的发展史 1990.2,ps1.0问世,1991.2,PS2.0发行,此后,进 ...
- CF917D. Stranger Trees & TopCoder13369. TreeDistance(变元矩阵树定理+高斯消元)
题目链接 CF917D:https://codeforces.com/problemset/problem/917/D TopCoder13369:https://community.topcoder ...
- OpenERP中自定义模块卸载失败,Postgres数据库删不掉数据库,OpenERP登录不了一直在加载的问题解决方案。
解决方案也就是删除掉不用的数据库,OE会提示当前有N个Session不让Drop数据库. 对于Postgres 9.1 版本,在pgAdmin中查询以下语句: SELECT pg_terminate_ ...
- Ubuntu16.04 下如何安装搜狗拼音输入法【亲测有效】
Ubuntu16.04 下如何安装搜狗拼音输入法[亲测有效] 一.添加fcitx键盘输入法系统[系统默认是iBus] 1.将下载源添加至系统源: sudo add-apt-repository p ...
- mssql 注入
注入查阅 .返回的是连接的数据库名 .作用是获取连接用户名 .将数据库备份到Web目录下面 ;backup database 数据库名 to disk='c:\inetpub\wwwroot\1.db ...
- 《LeetBook》leetcode题解(9):Palindrome Number[E]——回文数字
我现在在做一个叫<leetbook>的开源书项目,把解题思路都同步更新到github上了,需要的同学可以去看看 地址:https://github.com/hk029/leetcode 这 ...
- display:block、inline、inline-block的区别及应用案例
A.display:block就是将元素显示为块级元素. block元素的特点是: 1.总是在新行上开始: 2.高度,行高以及顶和底边距都可控制: 3.宽度缺省是它的容器的100%,除非设定一个宽度; ...
- orcale 之sql/plus set 命令
set 命令用于设置系统变量的值.通过set 命令设置的系统变量有很多,下面把最常用的罗列出来: 1. arraysize 用于从数据库中一次提取的行数,其默认为 15. SQL> show a ...
- 1-2 Mobx 入门实践之TodoList(官方Demo)
第一步:导入模块 import React, { Component } from 'react'; import { observable, autorun,computed } from 'mob ...