Curator实现zookeeper分布式锁简单案例
解决了传统分布式锁开发的繁琐,以及不能并发的问题
Curator官网:
https://curator.apache.org/
需要导入依赖:
<!-- https://mvnrepository.com/artifact/org.apache.curator/curator-recipes -->
<dependency>
**加粗样式** <groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>4.2.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.curator/curator-framework -->
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>4.2.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.curator/curator-client -->
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-client</artifactId>
<version>4.2.0</version>
</dependency>
流程连接客户端,创建锁
package com.example.zjh.zookeeper.CuratorFrame;
import lombok.SneakyThrows;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;
public class CuratorFrame {
public static void main(String[] args) {
// 分布式锁1
// 参数:客户端连接,节点名
InterProcessMutex lock1 = new InterProcessMutex(getLink(), "/locks");
// 分布式锁2
// InterProcessMutex lock2 = new InterProcessMutex(getLink(), "/locks");
// 线程
new Thread(new Runnable() {
@SneakyThrows
@Override
public void run() {
// lock1拿锁
lock1.acquire();
System.out.println("lock1拿到锁");
// lock1释放锁
lock1.release();
System.out.println("lock1解锁锁");
}
}).start();
}
private static CuratorFramework getLink() {
// 失败尝试构建次数(3000ms,3次)
final ExponentialBackoffRetry exponentialBackoffRetry = new ExponentialBackoffRetry(3000, 3);
// 构建连接
// 地址
final CuratorFramework linkZk = CuratorFrameworkFactory.builder().connectString("zookeeper集群地址")
// 连接超时时间,单位ms
.connectionTimeoutMs(20000)
// 会话超时时间,单位ms
.sessionTimeoutMs(20000)
// 重试
.retryPolicy(exponentialBackoffRetry).build();
// 启动客户端
linkZk.start();
// linkZk也能取到客户端节点以及数据
System.out.println("zookeeper连接成功");
return linkZk;
}
}