分布式重入共享锁:InterProcessMutex可重入共享锁,同一个线程可以重新调用获取,多次调用需要相应的释放资源zk分布式锁基础依赖
package com.miku.common.util.lock.zookeeper;
import com.miku.common.util.lock.support.AbstractZookeeperLock;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
/**
* 分布式重入共享锁
*
* @see java.util.concurrent.locks.ReentrantLock
*
* @author:panw.
*/
public class SharedReentrantLock extends AbstractZookeeperLock<InterProcessMutex> {
private final String lockKey = "shared-reentrant-lock";
/**
* Shared Reentrant Lock
*
* 获取可重入锁,阻塞直到可用,单实例{@code InterProcessMutex}获得几次锁需释放几次 <br>
* interProcessMutex {@link InterProcessMutex#InterProcessMutex} : <ul>
* <li>参数1: zk连接上下文{@link AbstractZookeeperLock#curatorFramework} </li>
* <li>参数2: zk锁路径,路径相同锁相同 </li>
* </ul>
*
* <b>注意:同一个线程可以重新调用获取。每次调用获取必须通过调用{@link SharedReentrantLock#release(String)}释放</b>
* @param var
* @throws Exception 抛出异常时,锁不在持有,获取锁失败,谨慎处理业务
*/
public void acquire(String var){
try {
super.lock(getReentrantLock(var));
} catch (Exception e) {
throw new IllegalStateException("获取重入共享锁失败=>" + e);
}
}
/**
* Shared Reentrant Lock
*
* @see com.miku.common.util.lock.zookeeper.SharedReentrantLock#acquire(String)
*
* @param var
* @param time 获取互斥锁:阻止直到可用或给定的时间到期
* @return 如果获得了互斥锁,则返回true,否则返回false
* @throws Exception 抛出异常时,锁不在持有,获取锁失败,谨慎处理业务
*/
public boolean acquire(String var,long time) throws Exception {
try {
return super.lock(getReentrantLock(var),time);
} catch (Exception e) {
throw new IllegalStateException("获取重入共享锁失败=>" + e);
}
}
private InterProcessMutex getReentrantLock(String var){
String key = lockKey + var;
InterProcessMutex interProcessMutex = null;
if (locks.containsKey(key)){
interProcessMutex = locks.get(key);
} else {
interProcessMutex = new InterProcessMutex(curatorFramework,var);
locks.put(key,interProcessMutex);
}
return interProcessMutex;
}
public void release(String var) throws Exception {
super.unlock(locks.get(lockKey + var));
}
}
结语:如有觉得不够力,不够用的请留言注明!!
博客原创:写作不易,转载请标明出处。文章地址:文章地址(๑˃∀˂๑)♪阿里嘎多(๑˃∀˂๑)♪
分布式锁-基于zookeeper客户端curator实现锁机制(一)锁基础
分布式锁-zookeeper-SharedLock基于InterProcessSemaphoreMutex(二)分布式共享锁
分布式锁-zookeeper-SharedReentrantLock基于InterProcessMutex(三)分布式重入共享锁
分布式锁-zookeeper-SharedReentrantReadWriteLock基于InterProcessReadWriteLock(四)分布式重入读写共享锁