简介

Curator是Netflix开源的一套ZooKeeper客户端框架. Netflix在使用ZooKeeper的过程中发现ZooKeeper自带的客户端太底层, 应用方在使用的时候需要自己处理很多事情, 于是在它的基础上包装了一下, 提供了一套更好用的客户端框架。

1、zookekeeper基本功能

     连接zookeeper,对节点进行crud、回调函数、判断节点是否存在

package bjsxt.curator.base;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.BackgroundCallback;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooKeeper.States;
import org.apache.zookeeper.data.Stat; public class CuratorBase { /** zookeeper地址 */
static final String CONNECT_ADDR = "192.168.0.4:2181,192.168.0.9:2181,192.168.0.6:2181";
/** session超时时间 */
static final int SESSION_OUTTIME = 5000;//ms public static void main(String[] args) throws Exception { //1 重试策略:初试时间为1s 重试10次
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 10);
//2 通过工厂创建连接
CuratorFramework cf = CuratorFrameworkFactory.builder()
.connectString(CONNECT_ADDR)
.sessionTimeoutMs(SESSION_OUTTIME)
.retryPolicy(retryPolicy)
// .namespace("super")
.build();
//3 开启连接
cf.start(); System.out.println(States.CONNECTED);
System.out.println(cf.getState()); // 新加、删除 //4 建立节点 指定节点类型(不加withMode默认为持久类型节点)、路径、数据内容
//cf.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath("/super/c1","c1内容".getBytes());
//5 删除节点
// cf.delete().guaranteed().deletingChildrenIfNeeded().forPath("/super"); // 读取、修改 //创建节点
/* cf.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath("/super/c1","c1内容".getBytes());
cf.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath("/super/c2","c2内容".getBytes());
//读取节点
String ret1 = new String(cf.getData().forPath("/super/c2"));
System.out.println("修改前c2节点====="+ret1);
//修改节点
cf.setData().forPath("/super/c2", "修改c2内容".getBytes());
String ret2 = new String(cf.getData().forPath("/super/c2"));
System.out.println("修改后c2节点====="+ret2);*/ // 绑定回调函数 ExecutorService pool = Executors.newCachedThreadPool();
cf.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT)
.inBackground(new BackgroundCallback() {
@Override
public void processResult(CuratorFramework cf, CuratorEvent ce) throws Exception {
System.out.println("code:" + ce.getResultCode());
System.out.println("type:" + ce.getType());
System.out.println("线程为:" + Thread.currentThread().getName());
}
}, pool)
.forPath("/super/c3","c3内容".getBytes());
Thread.sleep(Integer.MAX_VALUE); // 读取子节点getChildren方法 和 判断节点是否存在checkExists方法
/**
List<String> list = cf.getChildren().forPath("/super");
for(String p : list){
System.out.println(p);
} Stat stat = cf.checkExists().forPath("/super/c3");
System.out.println(stat); Thread.sleep(2000);
cf.delete().guaranteed().deletingChildrenIfNeeded().forPath("/super");
*/ //cf.delete().guaranteed().deletingChildrenIfNeeded().forPath("/super");
cf.close();
}
}

2、watcher方式一(监听当前节点发生变更)

package bjsxt.curator.watcher;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry; public class CuratorWatcher1 { /** zookeeper地址 */
static final String CONNECT_ADDR = "192.168.0.4:2181,192.168.0.9:2181,192.168.0.6:2181";
/** session超时时间 */
static final int SESSION_OUTTIME = 5000;//ms public static void main(String[] args) throws Exception { //1 重试策略:初试时间为1s 重试10次
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 10);
//2 通过工厂创建连接
CuratorFramework cf = CuratorFrameworkFactory.builder()
.connectString(CONNECT_ADDR)
.sessionTimeoutMs(SESSION_OUTTIME)
.retryPolicy(retryPolicy)
.build(); //3 建立连接
cf.start(); //4 建立一个cache缓存
final NodeCache cache = new NodeCache(cf, "/super", false);
cache.start(true);
cache.getListenable().addListener(new NodeCacheListener() {
/**
* <B>方法名称:</B>nodeChanged<BR>
* <B>概要说明:</B>触发事件为创建节点和更新节点,在删除节点的时候并不触发此操作。<BR>
* @see org.apache.curator.framework.recipes.cache.NodeCacheListener#nodeChanged()
*/
@Override
public void nodeChanged() throws Exception {
System.out.println("监听节点路径=====" + cache.getCurrentData().getPath());
System.out.println("数据=====" + new String(cache.getCurrentData().getData()));
System.out.println("状态=====" + cache.getCurrentData().getStat());
System.out.println("---------------------------------------");
}
}); Thread.sleep(1000);
cf.create().forPath("/super", "123".getBytes()); Thread.sleep(1000);
cf.setData().forPath("/super", "456".getBytes()); Thread.sleep(1000);
cf.delete().forPath("/super"); Thread.sleep(Integer.MAX_VALUE); }
}

3、watcher方式二(监听当前节点的子节点发生变更)

package bjsxt.curator.watcher;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.framework.recipes.cache.PathChildrenCache.StartMode;
import org.apache.curator.retry.ExponentialBackoffRetry; public class CuratorWatcher2 { /** zookeeper地址 */
static final String CONNECT_ADDR = "192.168.0.4:2181,192.168.0.9:2181,192.168.0.6:2181";
/** session超时时间 */
static final int SESSION_OUTTIME = 5000;//ms public static void main(String[] args) throws Exception { //1 重试策略:初试时间为1s 重试10次
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 10);
//2 通过工厂创建连接
CuratorFramework cf = CuratorFrameworkFactory.builder()
.connectString(CONNECT_ADDR)
.sessionTimeoutMs(SESSION_OUTTIME)
.retryPolicy(retryPolicy)
.build(); //3 建立连接
cf.start(); //4 建立一个PathChildrenCache缓存,第三个参数为是否接受节点数据内容 如果为false则不接受
PathChildrenCache cache = new PathChildrenCache(cf, "/super", true);
//5 在初始化的时候就进行缓存监听
cache.start(StartMode.POST_INITIALIZED_EVENT);
cache.getListenable().addListener(new PathChildrenCacheListener() {
/**
* <B>方法名称:</B>监听子节点变更<BR>
* <B>概要说明:</B>新建、修改、删除<BR>
* @see org.apache.curator.framework.recipes.cache.PathChildrenCacheListener#childEvent(org.apache.curator.framework.CuratorFramework, org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent)
*/
@Override
public void childEvent(CuratorFramework cf, PathChildrenCacheEvent event) throws Exception {
switch (event.getType()) {
case CHILD_ADDED:
System.out.println("新增子节点 =====" + event.getData().getPath());
break;
case CHILD_UPDATED:
System.out.println("修改子节点=====" + event.getData().getPath());
break;
case CHILD_REMOVED:
System.out.println("删除子节点=====" + event.getData().getPath());
break;
default:
break;
}
}
}); //创建本身节点不发生变化
cf.create().forPath("/super", "init".getBytes()); //添加子节点
Thread.sleep(1000);
cf.create().forPath("/super/c1", "c1内容".getBytes());
Thread.sleep(1000);
cf.create().forPath("/super/c2", "c2内容".getBytes()); //修改子节点
Thread.sleep(1000);
cf.setData().forPath("/super/c1", "c1更新内容".getBytes()); //删除子节点
Thread.sleep(1000);
cf.delete().forPath("/super/c2"); //删除本身节点
Thread.sleep(1000);
cf.delete().deletingChildrenIfNeeded().forPath("/super"); Thread.sleep(Integer.MAX_VALUE); }
}

Curator入门教程1的更多相关文章

  1. wepack+sass+vue 入门教程(三)

    十一.安装sass文件转换为css需要的相关依赖包 npm install --save-dev sass-loader style-loader css-loader loader的作用是辅助web ...

  2. wepack+sass+vue 入门教程(二)

    六.新建webpack配置文件 webpack.config.js 文件整体框架内容如下,后续会详细说明每个配置项的配置 webpack.config.js直接放在项目demo目录下 module.e ...

  3. wepack+sass+vue 入门教程(一)

    一.安装node.js node.js是基础,必须先安装.而且最新版的node.js,已经集成了npm. 下载地址 node安装,一路按默认即可. 二.全局安装webpack npm install ...

  4. Content Security Policy 入门教程

    阮一峰文章:Content Security Policy 入门教程

  5. gulp详细入门教程

    本文链接:http://www.ydcss.com/archives/18 gulp详细入门教程 简介: gulp是前端开发过程中对代码进行构建的工具,是自动化项目的构建利器:她不仅能对网站资源进行优 ...

  6. UE4新手引导入门教程

    请大家去这个地址下载:file:///D:/UE4%20Doc/虚幻4新手引导入门教程.pdf

  7. ABP(现代ASP.NET样板开发框架)系列之2、ABP入门教程

    点这里进入ABP系列文章总目录 基于DDD的现代ASP.NET开发框架--ABP系列之2.ABP入门教程 ABP是“ASP.NET Boilerplate Project (ASP.NET样板项目)” ...

  8. webpack入门教程之初识loader(二)

    上一节我们学习了webpack的安装和编译,这一节我们来一起学习webpack的加载器和配置文件. 要想让网页看起来绚丽多彩,那么css就是必不可少的一份子.如果想要在应用中增加一个css文件,那么w ...

  9. 转载:TypeScript 简介与《TypeScript 中文入门教程》

    简介 TypeScript是一种由微软开发的自由和开源的编程语言.它是JavaScript的一个超集,而且本质上向这个语言添加了可选的静态类型和基于类的面向对象编程.安德斯·海尔斯伯格,C#的首席架构 ...

随机推荐

  1. sql优化经历(转存+记录)

    sql优化经历 补充:看到这么多朋友对sql优化感兴趣,我又重新补充了下文章的内容,将更多关于sql优化的知识分享出来, 喜欢这篇文章的朋友给个赞吧,哈哈,欢迎交流,共同进步. 2015-4-30补充 ...

  2. 关于LoadRunner的迭代

    通过用lr做负载压力测试过程发现,如果设定不同的action迭代次数,每次得出的结果是不同的,曲线的表现形式也是不同的.这点就使我们会感觉困惑,为什么要设置action的迭代次数?以及对于不同的应用系 ...

  3. IDEA 开发环境中 调试Spark SQL及遇到问题解决办法

    1.问题 java.lang.OutOfMemoryError: PermGen space java.lang.OutOfMemoryError: Java heap space // :: WAR ...

  4. leetcode || 58、Length of Last Word

    problem: Given a string s consists of upper/lower-case alphabets and empty space characters ' ', ret ...

  5. Java使用JDBC连接随意类型数据库(mysql oracle。。)

    package cn.liz.test; import java.io.InputStream; import java.sql.Connection; import java.sql.Driver; ...

  6. java中static、this、super、final用途、用法及实例

    一.static 请先看下面这段程序: public class Hello { public static void main(String[] args){ //(1) System.out.pr ...

  7. Java优化技巧

    过早的优化是万恶之源. 优化了的代码可读性变差,可改性可适应性变差,可维护性变差. 远离过度优化,优化是个无底洞,把主要精力放在代码逻辑上. 优化的代码是活在当下的,是严重依赖硬件的,不利于表达永恒的 ...

  8. imageNamed 、imageWithContentsOfFile、 initWithContentsFile区别

    [UIImage imageNamed:]只适合与UI界面中的贴图的读取,较大的资源文件应该尽量避免使用 用UIImage加载本地图像最常用的是下面三种: 1.用imageNamed方法 [UIIma ...

  9. python学习笔记——信号模块signal

    基于python学习笔记——多进程间通信——Linux信号基础的学习基础,进一步学习Python标准库中的signal模块. 尽管signal是python中的模块,但是主要针对UNIX平台(比如Li ...

  10. python学习笔记011——闭包

    1 定义 定义:在计算机科学中,闭包是词法闭包的简称,是引用了自由变量的函数 简单地说:闭包就是能够读取其他函数内部变量的函数,闭包是将函数内部和函数外部连接起来的桥梁.——来源百度百科 2 描述 形 ...