有了上述分布式锁实现的基础之后,我们就很容易基于其实现一个分布式计数器。分布式计数器的一个典型场景是统计系统的在线人数。基于ZooKeeper的分布式计数器的实现思路页非常简单:
指定一个ZooKeeper数据节点作为计数器,多个应用实例在分布式锁的控制下,通过更新该数据节点的内容来实现计数功能。
Curator同样将这一系列逻辑封装在了DistributedAtomicInteger类中,从其类名我们可以看出这是一个可以在分布式环境中使用的原子整型,其具体使用方式可参考下面的示例程序。
使用Curator实现分布式计数器
// 使用Curator实现分布式计数器
public class Recipes_DistAtomicInt {
static String distatomicint_path = "/curator_recipes_distatomicint_path";
static CuratorFramework client = CuratorFrameworkFactory.builder().connectString("domain1.book.zookeeper:2181").retryPolicy(new ExponentialBackoffRetry(1000, 3)).build();
public static void main(String[] args) throws Exception {
client.start();
DistributedAtomicInteger atomicInteger = new DistributedAtomicInteger(client, distatomicint_path, new RetryNTimes(3, 1000));
AtomicValue<Integer> rc = atomicInteger.add(8);
System.out.println("Result: " + rc.succeeded());
}
}
哈哈