天天看點

redis實作分布式鎖一、首先需了解redis的幾個方法二、代碼實作

       最近公司使用Dubbo架構進行項目開發,在開發過程中遇到了線程同步問題,在網上查找了大部分資料後,發現可以使用redis或者zookeeper實作分布式鎖,雖然有些文章寫的不錯并給出了實作方案,但是自己在仔細推敲琢磨後發現其中還是有些邏輯問題,于是自己便動手寫了一個,直接上代碼。

一、首先需了解redis的幾個方法

1、setnx(key,value)如果redis資料庫中不存在key,将key的值設為value,傳回1;key存在時,不做任何操作,傳回0

2、getset(key,value)将key的值設為value并傳回舊值,如果key不存在則傳回null

3、del(key)删除key

二、代碼實作

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;



/**
 * @ClassName: DistributedLockHandler.java
 * @Description: 分布式鎖工具類
 * @Author:xiaoping
 * @CreateDate 2017年9月8日
 * @version:1.0
 *
 */

public class DistributedLockHandler {

	private static Logger logger = LoggerFactory.getLogger(DistributedLockHandler.class);
	private static final Integer Lock_Timeout = 3;
	private static final Map<String, String> map=new ConcurrentHashMap<String, String>();

	/**
	 * 擷取指定資料庫的鎖資源
	 *@param lockKey
	 *@param market
	 *@return
	 */
	private static boolean innerTryLock(String lockKey, int market) {

		boolean isSuccess = false;
		long currentTime = System.currentTimeMillis();
		String lockTimeDuration = String.valueOf(currentTime + Lock_Timeout + 1);
		long result = RedisUtil.setnx(lockKey, lockTimeDuration, market);
		if (result == 1) {
			isSuccess = true;
			map.put(lockKey, lockTimeDuration);
		} else {
			long oldValue = Long.valueOf(RedisUtil.get(lockKey, market));
			if (oldValue < System.currentTimeMillis()) {
				long getValue = Long.valueOf(RedisUtil.getSet(lockKey, lockTimeDuration, market));
				if (getValue == oldValue) {
					isSuccess = true;
					map.put(lockKey, lockTimeDuration);
				} else {
					isSuccess = false;
				}
			} else {
				isSuccess = false;
			}
		}
		return isSuccess;
	}

	/**
	 * 擷取指定資料庫的鎖資源,并指定逾時時間
	 *@param lockKey
	 *@param timeOut
	 *@param market
	 *@return
	 */
	public static boolean tryLock(String lockKey, Long timeOut, int market) {

		try {
			long currentTime = System.currentTimeMillis();
			boolean result = false;
			while (true) {
				if ((System.currentTimeMillis() - currentTime) / 1000 > timeOut) {
					logger.info("Execute DistributedLockHandler.tryLock method, Time out.");
					break;
				} else {
					result = innerTryLock(lockKey, market);
					if (result) {
						break;
					} else {
						logger.debug("Try to get the Lock,and wait 100 millisecond....");
						Thread.sleep(100);
					}
				}

			}
			return result;

		} catch (Exception e) {
			logger.error("Failed to run DistributedLockHandler.getLock method.", e);
			return false;
		}

	}

	/**
	 * 釋放指定資料庫的鎖資源
	 *@param lockKey
	 *@param currentTime
	 *@param market
	 */
	public void realseLock(String lockKey, long currentTime, int market) {
		String lockTimeDuration = RedisUtil.get(lockKey, market);
		if (map.get(lockKey)!=null&&map.get(lockKey).equals(lockTimeDuration)){
		    RedisUtil.del(lockKey, market);
		    map.remove(lockKey);              
           }
	}

}
           

繼續閱讀