通过Curator操作Zookeeper的例子(事务,分布式锁,原子自增))

Curator,用来操作zookeeper的瑞士军刀,首先感谢一下来自Netflix的 Jordan Zimmerman,是他给我们带来了如此美妙的工具。

    子节点缓存(PathChildrenCache)

            这个对象可以帮助我们实现根节点下面,子节点数据变化的回调通知。例如子节点的添加,修改,删除,通过PathChildrenCacheEvent
,我们可以在监听的事件里面得到当前节点的操作,然后做相应的操作。

《通过Curator操作Zookeeper的例子(事务,分布式锁,原子自增))》

其实,还有另外NodeCache也是可以缓存节点的变更,不过,它只能监听节点的新增,及修改,不能对节点的删除进行监听处理。

    节点操作事务处理(CuratorTransactionResult)

             当我们需要批量操作节点信息时,可以通过启用事务,来保证操作的原子性,类似数据库里面的多表操作.

《通过Curator操作Zookeeper的例子(事务,分布式锁,原子自增))》

  分布式锁(InterProcessMutex)

当我们需要在多个JVM之间同步对象的锁时,就需要用到这个,让你感觉就像一个JVM一样。

《通过Curator操作Zookeeper的例子(事务,分布式锁,原子自增))》

    分布式原子自增(DistributedAtomicLong)LONG类型

   类似于分布式计数器,实现多JVM共享一个计数器。

《通过Curator操作Zookeeper的例子(事务,分布式锁,原子自增))》

        它主要有两个构适方法,默认是基于乐观锁的实现 ,另外一个是互斥锁,

/**

* Creates in mutex promotion mode. The optimistic lock will be tried first using

* the given retry policy. If the increment does not succeed, a {@link InterProcessMutex} will be tried

* with its own retry policy

*

* @param client the client

* @param counterPath path to hold the value

* @param retryPolicy the retry policy to use

* @param promotedToLock the arguments for the mutex promotion

*/

public DistributedAtomicInteger(CuratorFramework client, String counterPath, RetryPolicy retryPolicy, PromotedToLock promotedToLock)

{

value = new DistributedAtomicValue(client, counterPath, retryPolicy, promotedToLock);

}

重点是第四个参数,互斥锁对象PromotedToLock,它有四个属性:

private final String        path;//zookeper节点

private final long          maxLockTime;//最大锁定时间

private final TimeUnit      maxLockTimeUnit;//时间单位

private final RetryPolicy   retryPolicy;// 重试策略

根据实际场景,选择合适的构造。

分布式原子自增(SharedCount)INTEGER类型

这是另外一个实现,跟上面差不多,需要手动start,close,唯一不同的就是它有一个监听器,可以监听每次计数器和连接的变化,这里,你可以做一些额外的操作。

《通过Curator操作Zookeeper的例子(事务,分布式锁,原子自增))》

其它,如选举,队列,锁等再另起章节说明了。

    原文作者:igool
    原文地址: https://www.jianshu.com/p/104715f5e79c
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞