(原) 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 ...
随机推荐
- 模拟淘宝购物,运用cookie,记录登录账号信息,并且记住购物车内所选的商品
1.登录界面 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEn ...
- Android开发学习之路-Android6.0运行时权限
在Android6.0以后开始,对于部分敏感的“危险”权限,需要在应用运行时向用户申请,只有用户允许的情况下这个权限才会被授予给应用.这对于用户来说,无疑是一个提升安全性的做法.那么对于开发者,应该怎 ...
- Android开发学习之路-指纹识别api
在android6.0之后谷歌对指纹识别进行了官方支持,今天还在放假,所以就随意尝试了一下这个api,但是遇到了各种各样的问题 ①在使用FingerPrintManager这个类实现的时候发现了很多问 ...
- Design6:选择合适的数据类型
数据库使用Table来存储海量的数据,细分Table结构,数据最终存储在Table Column中,因此,在设计Table Schema时,必须慎重选择Table Column的Data Type,数 ...
- EF-DbUpdateException解决方案
图二:
- OPEN CASCADE BSpline Curve Interpolation
OPEN CASCADE BSpline Curve Interpolation eryar@163.com Abstract. Global curve interpolation to point ...
- JavaScript == 、!=、===、!===的比较
; '; ; test == num //true 相同类型 相同值 test === num //true 相同类型 相同值 test !== num //false test与num类型相同,其值 ...
- Neutron 默认安全组规则 - 每天5分钟玩转 OpenStack(115)
Neutron 为 instance 提供了两种管理网络安全的方法: 安全组(Security Group)和虚拟防火墙. 安全组的原理是通过 iptables 对 instance 所在计算节点的网 ...
- ASP.NET中使用HttpWebRequest调用WCF
最近项目需要和第三网站进行数据交换,第三方网站基本都是RESTfull形式的API,但是也有的是Web Service,或者.NET里面的WCF.微软鼓励大家使用WCF替代Web Service. W ...
- HTML中哪些标签的值会被提交到服务器呢?
<form> <input name="">标签 <select name="">标签 <textarea name= ...