1. 程式人生 > >分散式鎖-zookeeper-SharedLock基於InterProcessSemaphoreMutex(二)分散式共享鎖

分散式鎖-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} <br> * interProcessMutex {@link InterProcessSemaphoreMutex#InterProcessSemaphoreMutex} : <ul> * <li>引數1: zk連線上下文{@link
AbstractZookeeperLock#curatorFramework} </li> * <li>引數2: zk鎖路徑,路徑相同鎖相同 </li> * </ul> * * @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)); } }