(原) 2.3 Curator使用
本文为原创文章,转载请注明出处,谢谢
Curator使用
1、jar包引入,演示版本为2.6.0,非maven项目,可以下载jar包导入到项目中
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>2.6.0</version>
</dependency> <dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>2.6.0</version>
</dependency>
2、RetryPolicy:重试机制
- ExponentialBackoffRetry:每次重试会增加重试时间baseSleepTimeMs
- ExponentialBackoffRetry(int baseSleepTimeMs, int maxRetries)
- ExponentialBackoffRetry(int baseSleepTimeMs, int maxRetries, int maxSleepMs)
- baseSleepTimeMs:基本重试时间差
- maxRetries:最大重试次数
- maxSleepMs:最大重试时间
- RetryNTimes
- RetryNTimes(int n, int sleepMsBetweenRetries)
- n:重试次数
- sleepMsBetweenRetries:每次重试间隔时间
- RetryNTimes(int n, int sleepMsBetweenRetries)
- RetryUntilElapsed
- RetryUntilElapsed(int maxElapsedTimeMs, int sleepMsBetweenRetries)
- maxElapsedTimeMs:最大重试时间
- sleepMsBetweenRetries:每次重试间隔时间
- RetryUntilElapsed(int maxElapsedTimeMs, int sleepMsBetweenRetries)
- BoundedExponentialBackoffRetry、RetryOneTime、SleepingRetry
3、创建Zookeeper连接
- 传统方式
示例:CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient("192.168.117.128:2181",5000,5000,retryPolicy);
API:
newClient(java.lang.String connectString, org.apache.curator.RetryPolicy retryPolicy) newClient(java.lang.String connectString, int sessionTimeoutMs, int connectionTimeoutMs, org.apache.curator.RetryPolicy retryPolicy)
- connectString:Zookeeper服务器地址
- retryPolicy:自定义重试机制
- sessionTimeoutMs:session超时时间
- connectionTimeoutMs:连接超时时间
- 链式方式
curatorFramework = CuratorFrameworkFactory.builder()
.connectString("192.168.117.128:2181")
//.authorization() 设置访问权限 设置方法同原生API
.sessionTimeoutMs(5000).connectionTimeoutMs(5000)
.retryPolicy(retryPolicy).build();
- 代码示例
public void createSession() {
//RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000,3);//基本重试间隔时间,重试次数(每次重试时间加长)
//RetryPolicy retryPolicy = new RetryNTimes(5,1000);//重试次数,重试间隔时间
RetryPolicy retryPolicy = new RetryUntilElapsed(5000,1000);//重试时间,重试间隔时间
//curatorFramework = CuratorFrameworkFactory.newClient("192.168.117.128:2181",5000,5000,retryPolicy);
curatorFramework = CuratorFrameworkFactory.builder()
.connectString("192.168.117.128:2181")
//.authorization() 设置访问权限 设置方法同原生API
.sessionTimeoutMs(5000).connectionTimeoutMs(5000)
.retryPolicy(retryPolicy).build();
curatorFramework.start();
}
4、创建节点
public void createNode() throws Exception {
createSession();
String path = curatorFramework.create()
.creatingParentsIfNeeded()//如果父节点没有自动创建
//.withACL()设置权限 权限创建同原生API
.withMode(CreateMode.PERSISTENT)//节点类型
.forPath("/note_curator/02", "02".getBytes());
System.out.println("path:"+path);
}
节点类型、权限设置详见2.1Zookeeper原生API使用
5、节点删除
public void del() throws Exception {
createSession();
curatorFramework.delete()
.guaranteed()//保证机制,出错后后台删除 直到删除成功
.deletingChildrenIfNeeded()//删除当前节点下的所有节点,再删除自身
.forPath("/note_curator");
}
6、获取子节点
public void getChildren() throws Exception {
createSession();
List<String> children = curatorFramework.getChildren().forPath("/note_curator");
System.out.println(children); }
7、获取节点信息
public void getData() throws Exception {
createSession();
Stat stat = new Stat();
byte[] u = curatorFramework.getData().storingStatIn(stat).forPath("/note_curator");
System.out.println(new String(u));
System.out.println(stat);
}
8、设置节点信息
public void setData() throws Exception {
createSession();
curatorFramework.setData()
//.withVersion(1) 设置版本号 乐观锁概念
.forPath("/note_curator/01", "shengke0815".getBytes());
}
9、是否存在节点
public void exists() throws Exception {
createSession();
Stat s = curatorFramework.checkExists().forPath("/note_curator");
System.out.println(s);
}
10、设置节点信息回调
ExecutorService executorService = Executors.newFixedThreadPool(5);//线程池
@Test
public void setDataAsync() throws Exception {
createSession();
curatorFramework.setData().inBackground(new BackgroundCallback() {//设置节点信息时回调方法
@Override
public void processResult(CuratorFramework curatorFramework, CuratorEvent curatorEvent) throws Exception { System.out.println(curatorFramework.getZookeeperClient());
System.out.println(curatorEvent.getResultCode());
System.out.println(curatorEvent.getPath());
System.out.println(curatorEvent.getContext());
}
},"shangxiawen",executorService).forPath("/note_curator","sksujer0815".getBytes());
Thread.sleep(Integer.MAX_VALUE);
}
API:
inBackground(org.apache.curator.framework.api.BackgroundCallback backgroundCallback, java.lang.Object o, java.util.concurrent.Executor executor);
backgroundCallback:自定义BackgroundCallback
- o:上下文信息,回调方法中curatorEvent.getContext()可获取此信息
- executor:线程池
11、监听节点改变事件
public void nodeListen() throws Exception {
createSession();
final NodeCache cache = new NodeCache(curatorFramework,"/note_curator");
cache.start();
cache.getListenable().addListener(new NodeCacheListener() {
@Override
public void nodeChanged() throws Exception {
System.out.println(new String(cache.getCurrentData().getData()));
System.out.println(cache.getCurrentData().getPath());
}
}); Thread.sleep(Integer.MAX_VALUE); }
12、监听子节点列表改变事件
public void nodeClildrenListen() throws Exception {
createSession();
final PathChildrenCache cache = new PathChildrenCache(curatorFramework,"/note_curator",true);
cache.start();
cache.getListenable().addListener(new PathChildrenCacheListener() {
@Override
public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent pathChildrenCacheEvent) throws Exception {
switch (pathChildrenCacheEvent.getType()){
case CHILD_ADDED:
System.out.println("add children");
System.out.println(new String(pathChildrenCacheEvent.getData().getData()));
System.out.println(new String(pathChildrenCacheEvent.getData().getPath()));
break;
case CHILD_REMOVED:
System.out.println("remove children");
System.out.println(new String(pathChildrenCacheEvent.getData().getData()));
System.out.println(new String(pathChildrenCacheEvent.getData().getPath()));
break;
case CHILD_UPDATED:
System.out.println("update children");
System.out.println(new String(pathChildrenCacheEvent.getData().getData()));
System.out.println(new String(pathChildrenCacheEvent.getData().getPath()));
break;
}
}
}); Thread.sleep(Integer.MAX_VALUE); }
下一节:3.1 Zookeeper应用 - Master选举
(原) 2.3 Curator使用的更多相关文章
- Curator 异步获取结果
原声的ZooKeeper 的CRUD API有同步和异步之分,对于异步API,需要传递AsyncCallback回调.对于getData,getChildren,exists这三个API,还可以设置W ...
- 8、Curator的监听机制
原生的zookeeper的监听API所实现的方法存在一些缺点,对于开发者来说后续的开发会考虑的细节比较多. Curator所实现的方法希望摒弃原声API 的不足,是开发看起来更加的简单,一些重连等操作 ...
- Zookeeper+Curator 分布式锁
本来想着基于zk临时节点,实现一下分布式锁,结果发现有curator框架.PS:原声API真的难用,连递归创建path都没有? 配置curator maven的时候,md配置了好几个小时,最后发现集中 ...
- Curator的监听机制
原生的zookeeper的监听API所实现的方法存在一些缺点,对于开发者来说后续的开发会考虑的细节比较多. Curator所实现的方法希望摒弃原声API 的不足,是开发看起来更加的简单,一些重连等操作 ...
- Apache Zookeeper Java客户端Curator使用及权限模式详解
这篇文章是让大家了解Zookeeper基于Java客户端Curator的基本操作,以及如何使用Zookeeper解决实际问题. Zookeeper基于Java访问 针对zookeeper,比较常用的J ...
- Zookeeper分布式锁实现Curator十一问
前面我们剖析了Redisson的源码,主要分析了Redisson实现Redis分布式锁的15问,理清了Redisson是如何实现的分布式锁和一些其它的特性.这篇文章就来接着剖析Zookeeper分布式 ...
- 【原】谈谈对Objective-C中代理模式的误解
[原]谈谈对Objective-C中代理模式的误解 本文转载请注明出处 —— polobymulberry-博客园 1. 前言 这篇文章主要是对代理模式和委托模式进行了对比,个人认为Objective ...
- 【原】FMDB源码阅读(三)
[原]FMDB源码阅读(三) 本文转载请注明出处 —— polobymulberry-博客园 1. 前言 FMDB比较优秀的地方就在于对多线程的处理.所以这一篇主要是研究FMDB的多线程处理的实现.而 ...
- 【原】Android热更新开源项目Tinker源码解析系列之一:Dex热更新
[原]Android热更新开源项目Tinker源码解析系列之一:Dex热更新 Tinker是微信的第一个开源项目,主要用于安卓应用bug的热修复和功能的迭代. Tinker github地址:http ...
随机推荐
- WebDriver--操控浏览器
前一篇讲述了元素的定位方法,现在开始练习如何写自动化测试脚本 我使用的编辑工具是PyCharm,今后该博客中所写的有关Python脚本,都是在该工具中编写的. WebDriver提供了控制浏览器大小. ...
- Android笔记——数据库升级与降级
一.概述 SQLite是Android内置的一个很小的关系型数据库.SQLiteOpenHelper是一个用来辅助管理数据库创建和版本升级问题的抽象类.我们可以继承这个抽象类,实现它的一些方法来对数据 ...
- 数据库中GETDATE()函数格式化时间
SELECT CONVERT(varchar(100), GETDATE(), 0): 05 16 2016 10:57AM SELECT CONVERT(varchar(100), GETDATE( ...
- 【转】Linq Group by
http://www.cnblogs.com/death029/archive/2011/07/23/2114877.html 1.简单形式: var q = from p in db.Product ...
- Atom支持Markdown和Latex
本篇博客主要用于记录Atom编辑器同时支持markdown和latex: 1.安装 安装方法1: (Windows系统)File->Settings->Install中搜索markdown ...
- Android实现播放视频
转载:http://www.bdqn.cn/news/201311/12100.shtml 使用VideoView播放视频 VideoView,用于播放一段视频媒体,它继承了SurfaceView,位 ...
- MVC实用架构设计(三)——EF-Code First(3):使用T4模板生成相似代码
前言 经过前面EF的<第一篇>与<第二篇>,我们的数据层功能已经较为完善了,但有不少代码相似度较高,比如负责实体映射的 EntityConfiguration,负责仓储操作的I ...
- 创建外网 ext_net - 每天5分钟玩转 OpenStack(104)
虽然外部网络是已经存在的网络,但我们还是需要在 Neutron 中定义外部网络的对象,这样 router 才知道如何将租户网络和外部网络连接起来. 上一节我们已经为创建外部网络配置了ML2,本节将通过 ...
- Puppet简易入门
一.查看官方提供的下载源 https://docs.puppet.com/guides/puppetlabs_package_repositories.html 二. 选择对应系统的下载源 因为本机是 ...
- 关于Repository、IUnitOfWork 在领域层和应用服务层之间的代码分布与实现
本来早就准备总结一下关于Repository.IUnitOfWork之间的联系以及在各层中的分布,直到看到田园里的蟋蟀发表的文章:<DDD 领域驱动设计-谈谈 Repository.IUnitO ...