Apache Curator Getting Started

Learn ZooKeeper

Curator users are assumed to know ZooKeeper. A good place to start is here: http://zookeeper.apache.org/doc/trunk/zookeeperStarted.html

Using Curator

The Curator JARs are available from Maven Central. The various artifacts are listed on the main page. Users of Maven, Gradle, Ant, etc. can easily include Curator into their build script.

Most users will want to use one of Curator's pre-built recipes. So, the curator-recipes is the correct artifact to use. If you only want a wrapper around ZooKeeper that adds connection management and retry policies, use curator-framework.

Getting a Connection

Curator uses Fluent Style. If you haven't used this before, it might seem odd so it's suggested that you familiarize yourself with the style.

Curator connection instances (CuratorFramework) are allocated from the CuratorFrameworkFactory. You only need one CuratorFramework object for each ZooKeeper cluster you are connecting to:

CuratorFrameworkFactory.newClient(zookeeperConnectionString, retryPolicy)

This will create a connection to a ZooKeeper cluster using default values. The only thing that you need to specify is the retry policy. For most cases, you should use:

RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3)
CuratorFramework client = CuratorFrameworkFactory.newClient(zookeeperConnectionString, retryPolicy);
client.start();

The client must be started (and closed when no longer needed).

Calling ZooKeeper Directly

Once you have a CuratorFramework instance, you can make direct calls to ZooKeeper in a similar way to using the raw ZooKeeper object provided in the ZooKeeper distribution. E.g.:

client.create().forPath("/my/path", myData)

The benefit here is that Curator manages the ZooKeeper connection and will retry operations if there are connection problems.

Recipes

Distributed Lock(分布式锁)
InterProcessMutex lock = new InterProcessMutex(client, lockPath);
if ( lock.acquire(maxWait, waitUnit) ) 
{
    try 
    {
        // do some work inside of the critical section here
    }
    finally
    {
        lock.release();
    }
}
Leader Election(leader选举)
LeaderSelectorListener listener = new LeaderSelectorListenerAdapter()
{
    public void takeLeadership(CuratorFramework client) throws Exception
    {
        // this callback will get called when you are the leader
        // do whatever leader work you need to and only exit
        // this method when you want to relinquish leadership
    }
}

LeaderSelector selector = new LeaderSelector(client, path, listener);
selector.autoRequeue();  // not required, but this is behavior that you will probably expect
selector.start();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值