Curator使用

Curator是Netflix公司一个开源的zookeeper客户端,在原生API接口上进行了包装,解决了很多ZooKeeper客户端非常底层的细节开发。同时内部实现了诸如Session超时重连,Watcher反复注册等功能,实现了Fluent风格的API接口,是使用最广泛的zookeeper客户端之一。

使用Curator需要依赖包:

guava-17.0.jar
zookeeper-3.4.6.jar
curator-framework-3.2.1.jar

创建连接:

public class CreateSession {public static void main(String[] args) throws Throwable  {RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);//刚开始重试间隔为1秒,之后重试间隔逐渐增加,最多重试不超过三次/*RetryPolicy retryPolicy1 = new RetryNTimes(3, 1000);//最大重试次数,和两次重试间隔时间RetryPolicy retryPolicy2 = new RetryUntilElapsed(5000, 1000);//会一直重试直到达到规定时间,第一个参数整个重试不能超过时间,第二个参数重试间隔//第一种方式CuratorFramework client = CuratorFrameworkFactory.newClient("192.168.0.3:2181", 5000,5000,retryPolicy);//最后一个参数重试策略*///第二种方式CuratorFramework client1 = CuratorFrameworkFactory.builder().connectString("192.168.0.3:2181").sessionTimeoutMs(5000)//会话超时时间.connectionTimeoutMs(5000)//连接超时时间.retryPolicy(retryPolicy).build();client1.start();String path = client1.create().creatingParentsIfNeeded()//若创建节点的父节点不存在会先创建父节点再创建子节点.withMode(CreateMode.EPHEMERAL)//withMode节点类型,.forPath("/curator/3","131".getBytes());System.out.println(path);List<String> list = client1.getChildren().forPath("/");System.out.println(list);//String re = new String(client1.getData().forPath("/curator/3"));//只获取数据内容Stat stat = new Stat();String re = new String(client1.getData().storingStatIn(stat)//在获取节点内容的同时把状态信息存入Stat对象.forPath("/curator/3"));System.out.println(re);System.out.println(stat);client1.delete().guaranteed()//保障机制,若未删除成功,只要会话有效会在后台一直尝试删除.deletingChildrenIfNeeded()//若当前节点包含子节点.withVersion(-1)//指定版本号.forPath("/curator");Thread.sleep(Integer.MAX_VALUE);}

修改节点数据:

    Stat stat = new Stat();String re = new String(client1.getData().storingStatIn(stat)//在获取节点内容的同时把状态信息存入Stat对象.forPath("/curator/3"));System.out.println(re);System.out.println(stat);Thread.sleep(10000);client1.setData().withVersion(stat.getVersion())//修改前获取一次节点数据得到版本信息.forPath("/curator/3", "111".getBytes());

若线程在sleep时,在另一个客户端修改了该节点数据,会抛出异常:

org.apache.zookeeper.KeeperException$BadVersionException: KeeperErrorCode = BadVersion for /curator/3

异步调用:

ExecutorService es = Executors.newFixedThreadPool(5);//线程池RetryPolicy retry = new ExponentialBackoffRetry(1000, 3);CuratorFramework client = CuratorFrameworkFactory.newClient("192.168.0.3:2181", 5000, 5000, retry);client.start();//Stat stat = client.checkExists().forPath("/node_1");//同步调用client.checkExists().inBackground(new BackgroundCallback() {@Overridepublic void processResult(CuratorFramework curator, CuratorEvent event) throws Exception {//传入客户端对象和事件System.out.println(event.getType());int re = event.getResultCode();//执行成功为0System.out.println(re);String path = event.getPath();System.out.println(path);Stat stat = event.getStat();System.out.println(stat);}},"123",es).forPath("/node_1");//把线程池es传给异步调用List<String> list = client.getChildren().forPath("/");System.out.println(list);Thread.sleep(Integer.MAX_VALUE);

事件监听:

    //节点监听RetryPolicy retry = new ExponentialBackoffRetry(1000, 3);CuratorFramework client = CuratorFrameworkFactory.newClient("192.168.0.3:2181", 5000, 5000, retry);client.start();final NodeCache cache = new NodeCache(client,"/node_1");cache.start();cache.getListenable().addListener(new NodeCacheListener() {@Overridepublic void nodeChanged() throws Exception {byte[] res = cache.getCurrentData().getData();System.out.println("data: " + new String(res));}});Thread.sleep(Integer.MAX_VALUE);//子节点监听@SuppressWarnings("resource")final PathChildrenCache cache = new PathChildrenCache(client,"/node_1",true);cache.start();cache.getListenable().addListener(new PathChildrenCacheListener() {@Overridepublic void childEvent(CuratorFramework curator, PathChildrenCacheEvent event) throws Exception {switch (event.getType()) {case CHILD_ADDED:System.out.println("add:" + event.getData());break;case CHILD_UPDATED:System.out.println("update:" + event.getData());break;case CHILD_REMOVED:System.out.println("remove:" + event.getData());break;default:break;}}});ACL权限:RetryPolicy retry = new ExponentialBackoffRetry(1000, 3);CuratorFramework client = CuratorFrameworkFactory.newClient("192.168.0.3:2181", 5000, 5000, retry);client.start();//ACL有IP授权和用户名密码访问的模式ACL aclRoot = new ACL(Perms.ALL,new Id("digest",DigestAuthenticationProvider.generateDigest("root:root")));List<ACL> aclList = new ArrayList<ACL>();aclList.add(aclRoot);String path = client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).withACL(aclList).forPath("/node_3/node_ACL","2".getBytes());System.out.println(path);CuratorFramework client1 =  CuratorFrameworkFactory.builder().connectString("192.168.0.3:2181").sessionTimeoutMs(5000)//会话超时时间.connectionTimeoutMs(5000)//连接超时时间.authorization("digest","root:root".getBytes())//权限访问.retryPolicy(retry).build();client1.start();String re = new String(client1.getData().forPath("/node_3/node_ACL"));System.out.println(re);

ZooKeeper——Curator客户端基本使用(笔记)相关推荐

  1. zookeeper curator客户端之增删改查

    zookeeper curator客户端之增删改查 zookeeper安装:https://www.cnblogs.com/zwcry/p/10272506.html curator客户端是Apach ...

  2. Zookeeper开源客户端框架Curator的简单使用

    为什么80%的码农都做不了架构师?>>>    Curator最初由Netflix的Jordan Zimmerman开发, Curator提供了一套Java类库, 可以更容易的使用Z ...

  3. Zookeeper的客户端Curator基本使用

    本文来说下Zookeeper的客户端Curator基本使用 文章目录 Curator概述 Curator包结构 创建会话 使用静态工程方法创建客户端 Fluent风格的Api创建会话 创建包含隔离命名 ...

  4. [转载]Zookeeper开源客户端框架Curator简介

    转载声明:http://macrochen.iteye.com/blog/1366136 Zookeeper开源客户端框架Curator简介 博客分类: Distributed Open Source ...

  5. 2.ZooKeeper客户端Curator「第三章 ZooKeeper Java客户端」「架构之路ZooKeeper理论和实战」

    前言 上一篇文章 介绍了zookeeper原生API的使用,使用过原生API不得不说,有很多的问题,比如:不能递归创建和删除节点.Watcher只能使用一次.还有很多可以解决分布式应用问题的api(比 ...

  6. Zookeeper 原生客户端、可视化工具 ZooInspector 、Apache Curator

    目录 Zookeeper 原生客户端 Apache Curator 开源客户端 可视化客户端工具 ZooInspector Zookeeper 原生客户端 1.类似 Redis 有多种 Java 客户 ...

  7. zookeeper开源客户端Curator介绍(六)

    原文地址,转载请注明出处: https://blog.csdn.net/qq_34021712/article/details/82872311     ©王赛超  上一篇文章 介绍了zookeepe ...

  8. Zookeeper Java 客户端 ——Apache Curator

    Zookeeper Java 客户端 --Apache Curator 一.基本依赖 二.客户端相关操作          2.1 创建客户端实例          2.2 重试策略          ...

  9. java curator_[java,zk]在 linux 上快速搭建 zookeeper curator 开发环境

    在这篇博客中简单介绍一下,如何快速的在 linux 操作系统上搭建使用 zookeeper 客户端 curator 编程的单机环境. 在前几篇博客中,介绍的是使用 zookeeper 原生提供的 AP ...

最新文章

  1. LeetCode中等题之区域和检索 - 数组可修改
  2. 可想实现一个自己的简单jQuery库?(五)
  3. des加密算法python代码_python des加密算法代码(pydes模块加密)
  4. QUIC实战(三) letsencrypt证书申请和自动续期
  5. java中的IO操作之File类
  6. 2021-09-08推荐系统有如下三大类算法
  7. 微计算机原理与接口半期考试,最新南京邮电大学微型计算机原理与接口技术期末考试试卷...
  8. 金融壹账通第一季营收10亿 沈崇锋:推进双重主要上市
  9. [Python-turtle]正弦定理能擦出多漂亮的火花?【1】
  10. linux中的lsof命令简介
  11. 导出Excel时出现80080005错误的解决办法
  12. 如何解决VC++6.0文件打不开
  13. Hannah荣获第六季完美童模全球总决赛全球人气总冠军
  14. vmware 虚拟机使用windows的 http/socks 代理
  15. Lucas定理扩展Lucas
  16. 2021-2027全球与中国同种异体人类软骨细胞市场现状及未来发展趋势
  17. 应届毕业生注意了,这些典型的学生思维正在阻碍你的职业发展
  18. delphi mysql.pas_mysql_pas DELPHI的 连接类源码,附带例程,无需ODBC驱动! VCL 269万源代码下载- www.pudn.com...
  19. Cause: java.lang.IllegalArgumentException: Result Maps collection already contains value for com.cor
  20. 第12周 oj 逆序输出

热门文章

  1. python简单案例4
  2. JSDoc3的简单使用
  3. 服务器304响应,网络---关于HTTP 304状态码的理解-Go语言中文社区
  4. 从原理到代码:大牛教你如何用 TensorFlow 亲手搭建一套图像识别模块 | AI 研习社...
  5. 迅龙万兆网络 驱动 linux,锐龙双万兆“小妖板” :ASRock 华擎 发布 X570D4I-2T ITX主板...
  6. SpringBoot项目8小时时差问题
  7. SSM框架专题-MyBatis框架老杜版从零入门笔记(下)
  8. 学习笔记 - 预祝CSDN 1024程序猿节日圆满成功
  9. python下载文件保存_Python根据URL地址下载文件并保存至对应目录的实现
  10. bzoj4997: [Usaco2017 Feb]Why Did the Cow Cross the Road III