Apache Curator 分布式锁的介绍,以及案例
可重入锁(InterProcessMutex):这种锁允许同一个客户端多次获取同一把锁而不会被阻塞,类似于Java中的ReentrantLock
。它通过在Zookeeper的指定路径下创建临时序列节点来实现锁的功能。如果获取锁失败,当前线程会监听前一个节点的变动情况并等待,直到被唤醒或超时
package com.zz.lock;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
public class CuratorReentrantLockExample {
private final String lockPath = "/curator/lock"; // 锁的Zookeeper路径
private CuratorFramework client; // Curator客户端
private InterProcessMutex mutex; // 可重入锁
// 初始化Curator客户端和可重入锁
public void init() {
// 设置Zookeeper服务地址
String connectString = "192.168.200.130:2181";
// 设置重试策略
ExponentialBackoffRetry retryPolicy = new ExponentialBackoffRetry(3000, 3);
// 创建Curator客户端
client = CuratorFrameworkFactory.newClient(connectString, retryPolicy);
client.start();
// 创建可重入锁
mutex = new InterProcessMutex(client, lockPath);
}
// 执行业务逻辑,使用可重入锁
public void executeBusinessLogic() {
try {
// 获取锁
mutex.acquire();
// 模拟业务逻辑
System.out.println("当前线程获得锁,开始执行业务逻辑。");
// 模拟重入逻辑
reentrantLock();
// 模拟业务逻辑
System.out.println("当前线程完成业务逻辑执行。");
} catch (Exception e) {
e.printStackTrace();
} finally {
// 确保释放锁
if (mutex.isAcquiredInThisProcess()) {
try {
mutex.release();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
// 模拟可重入逻辑
public void reentrantLock() {
try {
// 再次获取同一把锁
mutex.acquire();
System.out.println("当前线程重入成功,再次获得同一把锁。");
// 模拟一些操作...
} catch (Exception e) {
e.printStackTrace();
} finally {
// 释放锁
if (mutex.isAcquiredInThisProcess()) {
try {
mutex.release();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
// 程序入口
public static void main(String[] args) {
CuratorReentrantLockExample example = new CuratorReentrantLockExample();
example.init();
// 执行业务逻辑
example.executeBusinessLogic();
}
}
不可重入锁(InterProcessS