本文为原创文章,转载请注明出处,谢谢

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:每次重试间隔时间
  • RetryUntilElapsed
    • RetryUntilElapsed(int maxElapsedTimeMs, int sleepMsBetweenRetries)

      • maxElapsedTimeMs:最大重试时间
      • 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使用的更多相关文章

  1. Curator 异步获取结果

    原声的ZooKeeper 的CRUD API有同步和异步之分,对于异步API,需要传递AsyncCallback回调.对于getData,getChildren,exists这三个API,还可以设置W ...

  2. 8、Curator的监听机制

    原生的zookeeper的监听API所实现的方法存在一些缺点,对于开发者来说后续的开发会考虑的细节比较多. Curator所实现的方法希望摒弃原声API 的不足,是开发看起来更加的简单,一些重连等操作 ...

  3. Zookeeper+Curator 分布式锁

    本来想着基于zk临时节点,实现一下分布式锁,结果发现有curator框架.PS:原声API真的难用,连递归创建path都没有? 配置curator maven的时候,md配置了好几个小时,最后发现集中 ...

  4. Curator的监听机制

    原生的zookeeper的监听API所实现的方法存在一些缺点,对于开发者来说后续的开发会考虑的细节比较多. Curator所实现的方法希望摒弃原声API 的不足,是开发看起来更加的简单,一些重连等操作 ...

  5. Apache Zookeeper Java客户端Curator使用及权限模式详解

    这篇文章是让大家了解Zookeeper基于Java客户端Curator的基本操作,以及如何使用Zookeeper解决实际问题. Zookeeper基于Java访问 针对zookeeper,比较常用的J ...

  6. Zookeeper分布式锁实现Curator十一问

    前面我们剖析了Redisson的源码,主要分析了Redisson实现Redis分布式锁的15问,理清了Redisson是如何实现的分布式锁和一些其它的特性.这篇文章就来接着剖析Zookeeper分布式 ...

  7. 【原】谈谈对Objective-C中代理模式的误解

    [原]谈谈对Objective-C中代理模式的误解 本文转载请注明出处 —— polobymulberry-博客园 1. 前言 这篇文章主要是对代理模式和委托模式进行了对比,个人认为Objective ...

  8. 【原】FMDB源码阅读(三)

    [原]FMDB源码阅读(三) 本文转载请注明出处 —— polobymulberry-博客园 1. 前言 FMDB比较优秀的地方就在于对多线程的处理.所以这一篇主要是研究FMDB的多线程处理的实现.而 ...

  9. 【原】Android热更新开源项目Tinker源码解析系列之一:Dex热更新

    [原]Android热更新开源项目Tinker源码解析系列之一:Dex热更新 Tinker是微信的第一个开源项目,主要用于安卓应用bug的热修复和功能的迭代. Tinker github地址:http ...

随机推荐

  1. rem单位和em单位的使用

    今天弄了一点响应式的东西,本以为很快就可以弄好,结果还是绕晕了头,所以还是写下来方便下次看吧! 一开始我打算用百分比%来做响应式布局,后来算的很懵圈,就果断放弃了,哈哈是不是很明智. 接下来就是rem ...

  2. DPI深度包检测

    最近在读网络协议方面的论文,接触到DPI技术.博主是个小白,这里写些查到的笔记. 原文出处因为比较多,杂乱.百度文库和许多地方都有,就不贴链接了. 1. DPI 全称为"Deep Packe ...

  3. Hello Blog

    转眼之间,工作已经快五年了. 五年走的时候不觉得,当真正过来了,一回头,才真正体会到什么叫时间匆匆. 做了五年的技术,算是多有波折.想一想,做技术真的挺需要耐得住寂寞的,毕竟花花世界,压力太大,诱惑太 ...

  4. SQL Server 通过备份文件初始化复制

    一.本文所涉及的内容(Contents) 本文所涉及的内容(Contents) 背景(Contexts) 搭建过程(Process) 注意事项(Attention) 疑问(Questions) 参考文 ...

  5. LINQ系列:LINQ to DataSet的DataTable操作

    LINQ to DataSet需要使用System.Core.dll.System.Data.dll和System.Data.DataSetExtensions.dll,在项目中添加引用System. ...

  6. SQL Server中的高可用性(3)----复制

        在本系列文章的前两篇对高可用性的意义和单实例下的高可用性做了阐述.但是当随着数据量的增长,以及对RTO和RPO要求的严格,单实例已经无法满足HA/DR方面的要求,因此需要做多实例的高可用性.本 ...

  7. JS preventDefault ,stopPropagation ,return false

    所谓的事件有两种:监听事件和浏览器对特殊标签元素的默认行为事件.监听事件:在节点上被监听的事件操作,如 select节点的change事件,a节点的click事件.浏览器的默认事件:特定页面元素上带的 ...

  8. exe4j的使用

    下载:http://download.cnet.com/exe4j/3000-2070_4-144405.html 参考:http://blog.chinaunix.net/uid-25749806- ...

  9. ASP.NET Core的配置(4):多样性的配置来源[上篇]

    较之传统通过App.config和Web.config这两个XML文件承载的配置系统,ASP.NET Core采用的这个全新的配置模型的最大一个优势就是针对多种不同配置源的支持.我们可以将内存变量.命 ...

  10. 新作《ASP.NET MVC 5框架揭秘》正式出版

    ASP.NET MVC是一个建立在ASP.NET平台上基于MVC模式的Web开发框架,它提供了一种与Web Form完全不同的开发方式.ASP.NET Web Form借鉴了Windows Form基 ...