Zookeeper客户端(使用Curator)

三、使用curator客户端

在pom.xml中加入依赖

<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>2.12.0</version>
</dependency> <dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>2.11.0</version>
</dependency>

直接上代码:

 /**
* Project Name:mk-project <br>
* Package Name:com.suns.zookeeper.curator <br>
*
* @author mk <br>
* Date:2018-10-31 14:03 <br>
*/ package com.suns.zookeeper.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 org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat; import java.util.concurrent.TimeUnit; /**
* curator客户端使用
*
* 和原生zookeeper优点:
* 1.使用api更方便,功能更丰富
* 2.监听节点数据改变或者子节点变化,只需要订阅一次,便可以一直使用。而原生zookeeper的监听是一次性的,需要重复注册。
* 3.链式编程
*
* Curator包含了几个包:
* curator-framework:对zookeeper的底层api的一些封装
* curator-client:提供一些客户端的操作,例如重试策略等
* curator-recipes:封装了一些高级特性,如:Cache事件监听、选举、分布式锁、分布式计数器、分布式Barrier等
* ClassName: ZkCuratorTest <br>
* Description: <br>
* @author mk
* @Date 2018-10-31 14:03 <br>
* @version
*/
public class ZkCuratorTest { public static final String connect = "127.0.0.1:2181";
private static CuratorFramework curatorFramework = null;
private static String nodePath = "/curator1";
private static String nodeChildPath = "/curator1/n1/n11/n111/n1111"; public static void main(String[] args) throws Exception { //初始化
init(connect,5000); //监听节点数据改变或者子节点变化,只需要订阅一次,便可以一直使用。而原生zookeeper的监听是一次性的,需要重复注册。
listener(nodePath); //新增
create(nodePath,"n1");
//递归新增
createRecursion(nodeChildPath,"n1"); //查询
query(nodePath); TimeUnit.SECONDS.sleep(2); //修改
update(nodePath,"n11"); //单个节点删除
// delete(nodePath);
//递归删除
deleteRecursion(nodePath); } private static void deleteRecursion(String path) throws Exception {
Void aVoid = curatorFramework.delete().deletingChildrenIfNeeded().forPath(path);
System.out.println("delete:"+"["+path+"],result:"+aVoid);
} private static void delete(String path) throws Exception {
Void aVoid = curatorFramework.delete().forPath(path);
System.out.println("delete:"+"["+path+"],result:"+aVoid); } private static void update(String path, String data) throws Exception {
Stat stat = curatorFramework.setData().forPath(path, data.getBytes());
System.out.println("setData:"+"["+path+"],stat:"+stat); } private static void query(String path) throws Exception {
byte[] bytes = curatorFramework.getData().forPath(path);
System.out.println("query:"+"["+path+"],result:"+new String(bytes)); } private static void createRecursion(String path,String data) throws Exception {
String result = curatorFramework.create().creatingParentContainersIfNeeded().withMode(CreateMode.PERSISTENT).forPath(path, data.getBytes());
System.out.println("create:"+"["+path+"-->"+data+"],result:"+result); } private static void create(String path, String data) throws Exception {
// Stat stat = curatorFramework.checkExists().forPath(path);
// if(null != stat){
// System.out.println("节点["+path+"]已存在,不能新增");
// return;
// }
String result = curatorFramework.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(path, data.getBytes());
System.out.println("create:"+"["+path+"-->"+data+"],result:"+result);
} private static void listener(String path) throws Exception { //监听节点内容改变
final NodeCache nodeCache = new NodeCache(curatorFramework, path);
nodeCache.start();
/*nodeCache.getListenable().addListener(new NodeCacheListener() {
@Override
public void nodeChanged() throws Exception {
System.out.println("节点内容发生变化----->"+nodeCache.getCurrentData());
}
});*/ //使用lambda表达式-jdk1.8以上
nodeCache.getListenable().addListener(()->{System.out.println("节点内容发生变化----->"+nodeCache.getCurrentData());}); //监听子节点改变
final PathChildrenCache pathChildrenCache = new PathChildrenCache(curatorFramework, path, true);
pathChildrenCache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);
/* pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {
@Override
public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent pathChildrenCacheEvent) throws Exception {
switch (pathChildrenCacheEvent.getType() ){
case CHILD_ADDED:
System.out.println("新增子节点"+pathChildrenCache.getCurrentData());
break;
case CHILD_UPDATED:
System.out.println("更新子节点"+pathChildrenCache.getCurrentData());
break;
case CHILD_REMOVED:
System.out.println("删除子节点"+pathChildrenCache.getCurrentData());
break;
default:break;
}
}
});*/
//使用lambda表达式-jdk1.8以上
pathChildrenCache.getListenable().addListener((curatorFramework,pathChildrenCacheEvent)->
{switch (pathChildrenCacheEvent.getType() ){
case CHILD_ADDED:
System.out.println("新增子节点"+pathChildrenCache.getCurrentData());
break;
case CHILD_UPDATED:
System.out.println("更新子节点"+pathChildrenCache.getCurrentData());
break;
case CHILD_REMOVED:
System.out.println("删除子节点"+pathChildrenCache.getCurrentData());
break;
default:break;
}}); } private static void init(String connect, int sessionTimeout) {
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000,3);//重试策略,初始等待1s,重试3次
//通过工厂获得CuratorFramework
curatorFramework = CuratorFrameworkFactory.builder()
.connectString(connect).connectionTimeoutMs(sessionTimeout).retryPolicy(retryPolicy).build();
curatorFramework.start();//开启连接
System.out.println("curatorFramework start :" +connect);
} } 运行截图:


Zookeeper客户端使用(使用Curator)的更多相关文章

  1. zookeeper客户端使用第三方(Curator)封装的Api操作节点

    1.为什么使用Curator? Curator本身是Netflix公司开源的zookeeper客户端: Curator  提供了各种应用场景的实现封装: curator-framework  提供了f ...

  2. Zookeeper客户端Curator基本API

    在使用zookeper的时候一般不使用原生的API,Curator,解决了很多Zookeeper客户端非常底层的细节开发工作,包括连接重连.反复注册Watcher和NodeExistsExceptio ...

  3. Zookeeper客户端Curator的使用,简单高效

    Curator是Netflix公司开源的一个Zookeeper客户端,与Zookeeper提供的原生客户端相比,Curator的抽象层次更高,简化了Zookeeper客户端的开发量. 1.引入依赖: ...

  4. Zookeeper客户端Curator使用详解

    Zookeeper客户端Curator使用详解 前提 最近刚好用到了zookeeper,做了一个基于SpringBoot.Curator.Bootstrap写了一个可视化的Web应用: zookeep ...

  5. 7.5 zookeeper客户端curator的基本使用 + zkui

    使用zookeeper原生API实现一些复杂的东西比较麻烦.所以,出现了两款比较好的开源客户端,对zookeeper的原生API进行了包装:zkClient和curator.后者是Netflix出版的 ...

  6. zookeeper(六):Zookeeper客户端Curator的API使用详解

    简介 Curator是Netflix公司开源的一套zookeeper客户端框架,解决了很多Zookeeper客户端非常底层的细节开发工作,包括连接重连.反复注册Watcher和NodeExistsEx ...

  7. 转:Zookeeper客户端Curator使用详解

    原文:https://www.jianshu.com/p/70151fc0ef5d Zookeeper客户端Curator使用详解 前提 最近刚好用到了zookeeper,做了一个基于SpringBo ...

  8. Zookeeper客户端Apache Curator

    本文不对Zookeeper进行介绍,主要介绍Curator怎么操作Zookeeper. Apache Curator是Apache ZooKeeper的Java / JVM客户端库,Apache Zo ...

  9. Zookeeper系列三:Zookeeper客户端的使用(Zookeeper原生API如何进行调用、ZKClient、Curator)和Zookeeper会话

    一.Zookeeper原生API如何进行调用 准备工作: 首先在新建一个maven项目ZK-Demo,然后在pom.xml里面引入zk的依赖 <dependency> <groupI ...

随机推荐

  1. UFIDA

    充分匹配了‘用友’的中文品牌的含义,即‘与用户真诚合作,做用户可靠朋友’.其中‘U’代表‘User’,即用户:‘FID’表示忠诚.信任,来源于 Fidelity(诚实)等英文词的词根:助音词‘A’放在 ...

  2. Apache POI读取Excel

    1.pom.xml配置文件 <!-- 配置Apache POI --> <dependency> <groupId>org.apache.poi</group ...

  3. Mac搭建学习PHP环境

    在sublime text 3中学习PHP,编写PHP代码: 使用的xampp开发环境: 第一步,就是安装xampp,这个没啥可说的,根据自己的系统下载安装就好,我的是OSX;第二步,就是用XAMPP ...

  4. 使用shiro遇到的问题

    Caused by: java.lang.NoClassDefFoundError: net/sf/ehcache/CacheException 解决问题:缺少一个依赖的缓存jar 添加: <d ...

  5. java:shiroProject

    1.backend_system Maven Webapp:   LoginController.java: package com.shiro.demo.controller; import org ...

  6. 【学习笔记】使用python将最新的测试报告以附件的形式发到指定邮箱

    import smtplib, email, os, timefrom email.mime.multipart import MIMEMultipartfrom email.mime.text im ...

  7. 【Python开发】python重命名文件和遍历文件夹操作

    当前文件夹下,把所有文件名中的"50076"替换成"50092",用Python实现,代码所下: # encoding: utf-8 import os imp ...

  8. alembic常用命令和经典错误解决办法

  9. 使用PowerShell 自动创建DFS命名空间服务器

    运行环境:Windows Server 2012 R2 DFS命名空间概述 DFS命名空间 PowerShell脚本命令 Writing PowerShell DFS Scripts: Managin ...

  10. HDU 1260 Tickets (动态规划)

    Tickets Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Sub ...