首先来简单介绍下apache curator。
Apache Curator是Apache ZooKeeper的Java / JVM客户端库,Apache ZooKeeper是一种分布式协调服务。它包括一个高级API框架和实用程序,使Apache ZooKeeper更容易和更可靠。它还包括常见用例和扩展(如服务发现和Java 8异步DSL)的配方。
Curator项目组件

Maven依赖

分布式锁实现
org.apache.curator curator-recipes 4.1.0
public static void main(String[] args) {
String zookeeperConnectionString = "localhost:2181";
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
CuratorFramework client = CuratorFrameworkFactory.newClient(zookeeperConnectionString, retryPolicy);
client.start();
try {
//创建分布式锁, 锁空间的根节点路径为/curator/lock
InterProcessMutex lock = new InterProcessMutex(client, "/curator/lock");
if ( lock.acquire(1000, TimeUnit.SECONDS) )
{
try
{
// do some work inside of the critical section here
System.out.println("do some work inside of the critical section here");
}
finally
{
//完成业务流程, 释放锁
lock.release();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}