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.计数器 简介 ...
随机推荐
- 重要:C/C++变量的自动初始化
对于内置变量的自动初始化 代码1: #include<stdio.h> #define CONST 100 int *p1; ]; int b; static int c; main() ...
- HBase在搜狐内容推荐引擎系统中的应用
转自:http://www.aboutyun.com/thread-7297-1-1.html Facebook放弃Cassandra之后,对HBase 0.89版本进行了大量稳定性优化,使它真正成为 ...
- implicit declaration of function 'copy_from_user'
内核中使用copy_from_user()和copy_to_user()函数,编译出现错误: implicit declaration of function 'copy_from_user' 需要添 ...
- 解决只有单引号的Json格式转换成bean问题
objectMapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);单引号类似Json格式:{id:124463277,code:null ...
- while循环中,break,continue,return的差别
break 结束循环,跳出循环体: continue 结束本次循环.进行下次循环: return 跳出循环体所在的方法,相当于跳出循环体.
- 数据结构 http://www.cnblogs.com/sun-haiyu/p/7704654.html
数据结构与算法--从平衡二叉树(AVL)到红黑树 上节学习了二叉查找树.算法的性能取决于树的形状,而树的形状取决于插入键的顺序.在最好的情况下,n个结点的树是完全平衡的,如下图“最好情况”所示,此时树 ...
- sp_configure命令开启组件Agent XPs,数据库计划(Maintenance Plan)
新建“计划(Maintenance Plan)”时,记得执行计划需把SQL的“代理服务(SQL Server Agent)”也开启 出现对话框:“SQL Server 阻止了对组件 'Agent XP ...
- 网站性能测试PV到TPS的转换以及TPS的波动和淘宝性能测试要点
<淘宝性能测试白皮书V0.3> 性能测试的难点不在于测,在于测出的数据和实际的对照关系,以及测试出来的数据对性能的评估(到底是好,还是不好). 淘宝性能测试白皮书,解决了我的4个问题:1. ...
- Unity UI大小动态设置(Resize Unity UI RectTransform)
我们在开发过程中发现,要调整Unity UI元素的大小,RectTransform提供了sizeDelta属性可以用来动态修改RectTransform的大小,但同时我们也google到另外一个修改R ...
- 怎么让Word编辑公式又快又好
现在很多办公学习都是在电脑中进行的.很多文件论文都是在Word中编写定稿以后再打印成册或者去投稿.毫无疑问,在Word中编辑各种各样的文字与符号是一项现在社会中非常必要的技能,而这其中一项就是对公式的 ...