分布式锁-zookeeper-SharedLock基于InterProcessSemaphoreMutex(二)分布式共享锁

分布式共享锁:InterProcessSemaphoreMutex完全分布的全局同步锁,意味着在任何快照时间,没有两个客户端认为他们拥有相同的锁,继承上一篇分布式锁-zookeeper的AbstractZookeeperLock。细节与注意事项请看分布式锁-基于zookeeper客户端curator实现锁机制(一)锁基础

package com.miku.common.util.lock.zookeeper;

import com.miku.common.util.lock.support.AbstractZookeeperLock;
import org.apache.curator.framework.recipes.locks.InterProcessSemaphoreMutex;

/**
 * 分布式共享锁
 *
 * @author:panw.
 */
public class SharedLock extends AbstractZookeeperLock<InterProcessSemaphoreMutex> {

    private final String lockKey = "shared-lock";

    /**
     * Shared Lock
     *
     * 获取排他锁,阻塞直到可用,单实例{@code InterProcessSemaphoreMutex} 
* interProcessMutex {@link InterProcessSemaphoreMutex#InterProcessSemaphoreMutex} :
    *
  • 参数1: zk连接上下文{@link AbstractZookeeperLock#curatorFramework}
  • *
  • 参数2: zk锁路径,路径相同锁相同
  • *
* * @param var * @throws Exception 抛出异常时,锁不在持有,获取锁失败,谨慎处理业务 */
public void acquire(String var){ try { super.lock(getSharedLock(var)); } catch (Exception e) { throw new IllegalStateException("获取共享锁失败=>" + e); } } /** * Shared Lock * * @see com.miku.common.util.lock.zookeeper.SharedLock#acquire(String) * * @param var * @param time 获取互斥锁:阻止直到可用或给定的时间到期 * @return 如果获得了互斥锁,则返回true,否则返回false * @throws Exception 抛出异常时,锁不在持有,获取锁失败,谨慎处理业务 */ public boolean acquire(String var,long time) throws Exception { try { return super.lock(getSharedLock(var),time); } catch (Exception e) { throw new IllegalStateException("获取共享锁失败=>" + e); } } private InterProcessSemaphoreMutex getSharedLock(String var){ String key = lockKey + var; InterProcessSemaphoreMutex interProcessSemaphoreMutex = null; if (locks.containsKey(key)){ interProcessSemaphoreMutex = locks.get(key); }else { interProcessSemaphoreMutex = new InterProcessSemaphoreMutex(curatorFramework,var); locks.put(key,interProcessSemaphoreMutex); } return interProcessSemaphoreMutex; } public void release(String var) throws Exception { super.unlock(locks.get(lockKey + var)); } }

博客原创:写作不易,转载请标明出处。文章地址:http://blog.csdn.net/hatsune_miku_/article/details/79234079(๑˃∀˂๑)♪阿里嘎多(๑˃∀˂๑)♪
分布式锁-基于zookeeper客户端curator实现锁机制(一)锁基础
分布式锁-zookeeper-SharedLock基于InterProcessSemaphoreMutex(二)分布式共享锁
分布式锁-zookeeper-SharedReentrantLock基于InterProcessMutex(三)分布式重入共享锁
分布式锁-zookeeper-SharedReentrantReadWriteLock基于InterProcessReadWriteLock(四)分布式重入读写共享锁

你可能感兴趣的:(zookeeper,curator,apache,分布式锁)