07.Curator计数器
1.SharedCount
- SharedCount - 管理一个共享的整数。所有看同样的路径客户端将有共享的整数(考虑ZK的正常一致性保证)的最高最新的值。
- SharedCountReader - 一个共享的整数接口,并允许监听改变它的值。
- SharedCountListener - 用于监听共享整数发生变化的监听器。
public class SharedCounterExample implements SharedCountListener{private static final int QTY = 5;private static final String PATH = "/examples/counter";public static void main(String[] args) throws IOException, Exception{final Random rand = new Random();SharedCounterExample example = new SharedCounterExample();CuratorFramework client = CuratorFrameworkFactory.newClient("127.0.0.1:2181", new ExponentialBackoffRetry(1000, 3));client.start();SharedCount baseCount = new SharedCount(client, PATH, 0);baseCount.addListener(example);baseCount.start();List<SharedCount> examples = Lists.newArrayList();ExecutorService service = Executors.newFixedThreadPool(QTY);for (int i = 0; i < QTY; ++i){final SharedCount count = new SharedCount(client, PATH, 0);examples.add(count);Callable<Void> task = new Callable<Void>(){@Overridepublic Void call() throws Exception{count.start();Thread.sleep(rand.nextInt(10000));count.setCount(rand.nextInt(10000));System.out.println("计数器当前值:" + count.getVersionedValue().getValue());System.out.println("计数器当前版本:" + count.getVersionedValue().getVersion());System.out.println("trySetCount:" + count.trySetCount(count.getVersionedValue(), 123));return null;}};service.submit(task);}service.shutdown();service.awaitTermination(10, TimeUnit.MINUTES);for (int i = 0; i < QTY; ++i){examples.get(i).close();}baseCount.close();client.close();System.out.println("OK!");}@Overridepublic void stateChanged(CuratorFramework client, ConnectionState newState){System.out.println("连接状态: " + newState.toString());}@Overridepublic void countHasChanged(SharedCountReader sharedCount, int newCount) throws Exception{System.out.println("计数器值改变:" + newCount);}}
连接状态: CONNECTED计数器当前值:1684计数器当前版本:11trySetCount:true计数器值改变:123计数器当前值:8425计数器当前版本:13trySetCount:true计数器值改变:123计数器当前值:9369计数器当前版本:15trySetCount:true计数器值改变:123计数器当前值:4075计数器当前版本:17trySetCount:true计数器值改变:123计数器当前值:9221计数器当前版本:19trySetCount:trueOK!

2.DistributedAtomicLong
public class DistributedAtomicLong implements DistributedAtomicNumber<Long>{private final DistributedAtomicValue value;......}public class DistributedAtomicValue{......AtomicValue<byte[]> trySet(MakeValue makeValue) throws Exception{MutableAtomicValue<byte[]> result = new MutableAtomicValue<byte[]>(null, null, false);tryOptimistic(result, makeValue);if ( !result.succeeded() && (mutex != null) ){tryWithMutex(result, makeValue);}return result;}......}
- get(): 获取当前值
- increment(): 加一
- decrement(): 减一
- add(): 增加特定的值
- subtract(): 减去特定的值
- trySet(): 尝试设置计数值
- forceSet(): 强制设置计数值
public class DistributedAtomicLongExample{private static final int QTY = 5;private static final String PATH = "/examples/counter";public static void main(String[] args) throws IOException, Exception{final Random rand = new Random();CuratorFramework client = CuratorFrameworkFactory.newClient("127.0.0.1:2181", new ExponentialBackoffRetry(1000, 3));client.start();List<DistributedAtomicLong> examples = Lists.newArrayList();ExecutorService service = Executors.newFixedThreadPool(QTY);for (int i = 0; i < QTY; ++i){final DistributedAtomicLong count = new DistributedAtomicLong(client, PATH, new RetryNTimes(10, 10));examples.add(count);Callable<Void> task = new Callable<Void>(){@Overridepublic Void call() throws Exception{try{Thread.sleep(1000 + rand.nextInt(10000));AtomicValue<Long> value = count.increment();System.out.println("修改成功: " + value.succeeded());if (value.succeeded()){System.out.println("修改之前的值:" + value.preValue() + " | 修改之后的值:" + value.postValue());}}catch (Exception e){e.printStackTrace();}return null;}};service.submit(task);}service.shutdown();service.awaitTermination(10, TimeUnit.MINUTES);client.close();System.out.println("OK!");}}
修改成功: true修改之前的值:0 | 修改之后的值:1修改成功: true修改之前的值:1 | 修改之后的值:2修改成功: true修改之前的值:2 | 修改之后的值:3修改成功: true修改之前的值:3 | 修改之后的值:4修改成功: true修改之前的值:4 | 修改之后的值:5OK!

-------------------------------------------------------------------------------------------------------------------------------
07.Curator计数器的更多相关文章
- zookeeper之分布式锁以及分布式计数器(通过curator框架实现)
有人可能会问zookeeper我知道,但是curator是什么呢? 其实curator是apachede针对zookeeper开发的一个api框架是apache的顶级项目 他与zookeeper原生a ...
- PHP学习之[第07讲]PHP5.4 文件操作函数 之 图片计数器的实例
1.filetype():输出文件类型: 2.stat():获取文件的基本属性的数组: 3.clearstatcache().is_executable().isDir().idFile().scan ...
- Zookeeper开源客户端框架Curator简介
Curator是Netflix开源的一套ZooKeeper客户端框架. Netflix在使用ZooKeeper的过程中发现ZooKeeper自带的客户端太底层, 应用方在使用的时候需要自己处理很多事情 ...
- Zookeeper开源客户端框架Curator简介[转]
Curator是Netflix开源的一套ZooKeeper客户端框架. Netflix在使用ZooKeeper的过程中发现ZooKeeper自带的客户端太底层, 应用方在使用的时候需要自己处理很多事情 ...
- Python学习笔记——基础篇2【第三周】——计数器、有序字典、元组、单(双)向队列、深浅拷贝、函数、装饰器
目录 1.Python计数器Counter 2.Python有序字典OrderredDict 3.Python默认字典default 4.python可命名元组namedtuple 5.Python双 ...
- zookeeper(2)-curator
一.Curator介绍 zookeeper的提交人也说过,curator对于zookeeper而言就像是guava对于java差不多,更加优雅高效. 而且之前的zookeeper原生API,往往因为2 ...
- 15. 使用Apache Curator管理ZooKeeper
Apache ZooKeeper是为了帮助解决复杂问题的软件工具,它可以帮助用户从复杂的实现中解救出来. 然而,ZooKeeper只暴露了原语,这取决于用户如何使用这些原语来解决应用程序中的协调问题. ...
- Zookeeper客户端Curator基本API
在使用zookeper的时候一般不使用原生的API,Curator,解决了很多Zookeeper客户端非常底层的细节开发工作,包括连接重连.反复注册Watcher和NodeExistsExceptio ...
- MapReduce 计数器简介
转自:http://my.oschina.net/leejun2005/blog/276891?utm_source=tuicool&utm_medium=referral 1.计数器 简介 ...
随机推荐
- 如何退出Activity?如何安全退出已调用多个Activity的Application?
对于单一Activity的应用来说,退出很简单,直接finish()即可. 1.抛异常强制退出: 该方法通过抛异常,使程序ForceClose. 验证可以,但是,需要解决的问题是,如何使程序结束掉,而 ...
- 【转】OPenGL MFC绘图
一.简介 GDI是通过设备句柄(Device Context以下简称"DC")来绘图,而OpenGL则需要绘制环境(Rendering Context,以下简称"RC&q ...
- HTML input只能输入数字
onkeyup="this.value=this.value.replace(/[^0-9]/g,'')" onafterpaste="this.value=this.v ...
- Maven-使用及常见问题
一.Maven是什么? 管理jar包用的,以前jar包是自己下载,然后放在lib下,然后add build Path,Maven环境下,只需要添加坐标(实际是xml片段)便会根据坐标自行下载. 二.M ...
- jquery获取html元素的绝对位置和相对位置的方法
绝对位置坐标: 代码如下: $("#elem").offset().top$("#elem").offset().left 相对父元素的位置坐标: 代码如下: ...
- linux mint 19解决 输入法问题
安装搜狗后出现 You're currently running Fcitx with GUI, but fcitx-configtool couldn't be found, the package ...
- mysql数据库中,通过一条insert into语句,同时插入多个值
需求描述: 今天在看一本mysql的书籍,发现一个mysql中insert into好用的技巧,就是通过 1条insert into语句,插入多行数据,而不是多个insert into语句.在此记录下 ...
- 非常不错的前端框架Kendo-ui
近期公司在做重构,准备换前端框架由Extjs换kendo-ui,问什么要换框架呢?主要有以下几个原因: Extjs太重,偏向后端语言,前端写起来费劲 Extjs执行太慢(这是主要原因),因为Extjs ...
- ROS文件系统介绍--2
ros初级核心教程--ROS文件系统介绍(原创博文,转载请标明出处--周学伟http://www.cnblogs.com/zxouxuewei/) 1.ROS文件系统介绍: 1.1.预备工作:本教程中 ...
- C#读取Excel日期时间
//如果为20171219 if (dt.Rows[i][title].ToString().Trim().Length == 8) { realDate = dt.Rows[i][title].To ...