通过Curator操作Zookeeper的简单例子代码
Curator主要解决了三类问题: 一个是ZooKeeper client与ZooKeeper server之间的连接处理; 一个是提供了一套Fluent风格的操作API; 一个是ZooKeeper各种应用场景(recipe, 比如共享锁服务, 集群领导选举机制)抽象封装.
Curator几个组成部分
- Client: 是ZooKeeper客户端的一个替代品, 提供了一些底层处理和相关的工具方法.
- Framework: 用来简化ZooKeeper高级功能的使用, 并增加了一些新的功能, 比如管理到ZooKeeper集群的连接, 重试处理
- Recipes: 实现了通用ZooKeeper的recipe, 该组件建立在Framework的基础之上
- Utilities:各种ZooKeeper的工具类
- Errors: 异常处理, 连接, 恢复等.
- Extensions: recipe扩展
Framework 方法说明:
- create(): 发起一个create操作. 可以组合其他方法 (比如mode 或background) 最后以forPath()方法结尾
- delete(): 发起一个删除操作. 可以组合其他方法(version 或background) 最后以forPath()方法结尾
- checkExists(): 发起一个检查ZNode 是否存在的操作. 可以组合其他方法(watch 或background) 最后以forPath()方法结尾
- getData(): 发起一个获取ZNode数据的操作. 可以组合其他方法(watch, background 或get stat) 最后以forPath()方法结尾
- setData(): 发起一个设置ZNode数据的操作. 可以组合其他方法(version 或background) 最后以forPath()方法结尾
- getChildren(): 发起一个获取ZNode子节点的操作. 可以组合其他方法(watch, background 或get stat) 最后以forPath()方法结尾
- inTransaction(): 发起一个ZooKeeper事务. 可以组合create, setData, check, 和/或delete 为一个操作, 然后commit() 提交
import java.awt.Event;
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.framework.api.CuratorEventType;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
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.retry.RetryUntilElapsed;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
public class TestCurator {
public static void main(String[] args) throws Exception {
RetryPolicy retryPolicy = new RetryUntilElapsed(5000, 1000);
ExecutorService es = Executors.newFixedThreadPool(5); // 线程池
CuratorFramework client = CuratorFrameworkFactory.builder().connectString("192.168.1.134")
.sessionTimeoutMs(5000).connectionTimeoutMs(5000).retryPolicy(retryPolicy).build();
client.start();
// 1.创建节点 (临时节点)
// String path1 =
// client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath("/node_1",
// "I'm NODE_1".getBytes());
// System.out.println("创建node_1" + path1);
// String path2 =
// client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL)
// .forPath("/node_1/node_1_1", "I'm NODE_1_1".getBytes());
// System.out.println("创建" + path2);
// String path3 =
// client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL)
// .forPath("/node_1/node_1_3", "I'm NODE_1_3".getBytes());
// System.out.println("创建" + path3);
// 2.删除节点
// 普通单节点:直接指定删除路径 ; 需要服务端进行版本检验:withVersion;
// 删除子节点:deletingChildrenIfNeeded; 保障机制:guarangteed。
// client.delete().guaranteed().deletingChildrenIfNeeded().forPath("/node_1/1");
// 3.查看子节点列表
List<String> clist = client.getChildren().forPath("/node_1");
System.out.println("子节点: " + clist.toString());
// 4.获取节点的数据内容 返回字节数组; 获取节点状态信息:storingStatIN
Stat stat = new Stat();
byte[] ret = client.getData().storingStatIn(stat).forPath("/node_1");
System.out.println("数据: " + new String(ret));
System.out.println("节点状态信息: " + stat);
// 5.修改数据
client.setData().withVersion(stat.getVersion()).forPath("/node_1", "我是node_1".getBytes());
byte[] ret1 = client.getData().storingStatIn(stat).forPath("/node_1");
System.out.println("修改后的数据: " + new String(ret1));
// 6.查看是否存在 Stat s = client.checkExists().forPath("") 存在则返回stat对象,否则返回空
// 异步调用
client.checkExists().inBackground(new BackgroundCallback() {
public void processResult(CuratorFramework arg0, CuratorEvent arg1) throws Exception {
// TODO Auto-generated method stub
CuratorEventType t = arg1.getType();
System.out.println("事件类型:"+t);
System.out.println("返回码: " + arg1.getResultCode());// 返回码 成功返回码为0
System.out.println("触发事件的节点路径: " + arg1.getPath());
System.out.println("子节点: " + arg1.getChildren());
System.out.println("数据内容: " + arg1.getData());
System.out.println("节点状态信息1: " + arg1.getStat());
System.out.println("上下文: " + arg1.getContext()); // 上下文 ,执行异步调用时传入额外参数供我们使用
}
}, "123", es).forPath("/node_1");
// 7.节点监听器 只能监听节点的新增,及修改,不能对节点的删除进行监听处理。
final NodeCache cache = new NodeCache(client, "/node_1");
cache.start();
cache.getListenable().addListener(new NodeCacheListener() {
public void nodeChanged() throws Exception {
// TODO Auto-generated method stub
byte[] ret = cache.getCurrentData().getData(); //拿到当前结点的最新数据
System.out.println("新数据: " + new String(ret));
}
});
// 8。子节点监听器 子节点的添加,修改,删除
final PathChildrenCache cache2 = new PathChildrenCache(client, "/node_1", true);
cache2.start();
cache2.getListenable().addListener(new PathChildrenCacheListener() {
public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
// TODO Auto-generated method stub
switch (event.getType()) {
case CHILD_ADDED:
System.out.println("CHILD_ADDED:"+event.getData());
break;
case CHILD_UPDATED:
System.out.println("CHILD_UPDATED:"+event.getData());
break;
case CHILD_REMOVED:
System.out.println("CHILD_REMOVED:"+event.getData());
break;
default:
break;
}
}
});
Thread.sleep(Integer.MAX_VALUE);
}
}
通过Curator操作Zookeeper的简单例子代码的更多相关文章
- Java curator操作zookeeper获取kafka
Java curator操作zookeeper获取kafka Curator是Netflix公司开源的一个Zookeeper客户端,与Zookeeper提供的原生客户端相比,Curator的抽象层次更 ...
- 使用Curator操作ZooKeeper
Curator是Netflix公司开源的一个ZooKeeper client library,用于简化ZooKeeper客户端编程.它包含如下模块: Framework:Framework是ZooKe ...
- curator操作zookeeper
使用zookeeper原生API实现一些复杂的东西比较麻烦.所以,出现了两款比较好的开源客户端,对zookeeper的原生API进行了包装:zkClient和curator.后者是Netflix出版的 ...
- [C++] socket - 3 [线程简单例子 代码]
#include<windows.h> #include<stdio.h> DWORD WINAPI myfun1(LPVOID lpParameter);//声明线程函数 D ...
- ArcEngine创建IElement简单例子
转自IT-GIS终结者原文ArcEngine创建IElement简单例子 代码下载地址:http://files.cnblogs.com/ogis/MapControlApplication2.rar ...
- 使用curator框架简单操作zookeeper 学习笔记
Curator 操作是zookeeper的优秀api(相对于原生api),满足大部分需求.而且是Fluent流式api风格. 参考文献:https://www.jianshu.com/p/70151f ...
- Python 基于Python及zookeeper实现简单分布式任务调度系统设计思路及核心代码实现
基于Python及zookeeper实现简单分布式任务调度系统设计思路及核心代码实现 by:授客 QQ:1033553122 测试环境 功能需求 实现思路 代码实践(关键技术点实现) 代码模块组织 ...
- C#使用互斥量(Mutex)实现多进程并发操作时多进程间线程同步操作(进程同步)的简单示例代码及使用方法
本文主要是实现操作系统级别的多进程间线程同步(进程同步)的示例代码及测试结果.代码经过测试,可供参考,也可直接使用. 承接上一篇博客的业务场景[C#使用读写锁三行代码简单解决多线程并发写入文件时线程同 ...
- Java代码操作zookeeper
.personSunflowerP { background: rgba(51, 153, 0, 0.66); border-bottom: 1px solid rgba(0, 102, 0, 1); ...
随机推荐
- AlertView with password
1. setAlertViewStyle:UIAlertViewStyleSecureTextInput UIAlertView *alertView = [[UIAlertView alloc] i ...
- Codeforces Round #328 (Div. 2) D. Super M 虚树直径
D. Super M Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/592/problem/D ...
- Android版本号的识别——$(PLATFORM_VERSION)
#/******************************************************************************#*@file Android.mk#* ...
- 关于Android与pc通信时中文乱码的分析和解决
初步实现了Android与pc服务器的通信之后,又碰到了传说中令人头疼不已的中文乱码问题.既然出现了乱码,那么原因自然是协议不通了.我们知道eclipse中默认的编码标准是GBK,而安卓程序开发所默认 ...
- android UI进阶之实现listview中checkbox的多选与记录
今天继续和大家分享涉及到listview的内容.在很多时候,我们会用到listview和checkbox配合来提供给用户一些选择操作.比如在一个 清单页面,我们需要记录用户勾选了哪些条目.这个的实现并 ...
- sysbench 安装 原创
1.下载sysbench version 0.5 https://github.com/akopytov/sysbench 2. [root@server1 sysbench-0.5]# pwd/ro ...
- UNIX基础知识之系统调用与库函数的区别与联系
上图为UNIX操作系统的体系结构.内核的接口被称为系统调用(system call),公用函数库构建在系统调用接口之上,应用软件既可以使用公用函数库,也可直接使用系统调用. 更详细的说明如下: 所有操 ...
- SQL SERVER 中identity用法
在数据库中, 常用的一个流水编号通常会使用 identity 栏位来进行设置, 这种编号的好处是一定不会重覆, 而且一定是唯一的, 这对table中的唯一值特性很重要, 通常用来做客户编号, 订单编号 ...
- php编程中容易忽略的地方
一:fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] ...
- Pass value from child popup window to parent page window using JavaScript--reference
Here Mudassar Ahmed Khan has explained how to pass value from child popup window to parent page wind ...