在部分情況下,要保證操作在整個集群內(nèi)是同步的,以操作庫存為例,多個減操作需要同步,常見的有兩種方式:
- 采用類CAS的方式,先查詢庫存,然后使用update xxx set num=num-1 where id=:id and num=:num;這樣可保證庫在本次修改之前未被修改;
- 使用分布式鎖,保證同時只有一個地方在修改庫存。
這里向大家展示一個基于redis的分布式鎖。主要涉及三個類:
- DistributedLockUtil對外提供獲取分布式鎖的方法;
- DistributedLock 分布式鎖接口,定義分布式鎖支持的方法,主要有acquire和release;
- JedisLock實現(xiàn)DistributedLock接口,是基于redis的分布鎖實現(xiàn) ;
需要使用StringRedisTemplate,如對spring boot整合redis不熟悉,請參考spring boot項目實戰(zhàn):redis.
DistributedLock接口
public interface DistributedLock {
/**
* 獲取鎖
* @author yangwenkui
* @time 2016年5月6日 上午11:02:54
* @return
* @throws InterruptedException
*/
public boolean acquire();
/**
* 釋放鎖
* @author yangwenkui
* @time 2016年5月6日 上午11:02:59
*/
public void release();
}
JedisLock基于redis的分布式鎖實現(xiàn)
public class JedisLock implements DistributedLock{
private static Logger logger = LoggerFactory.getLogger(JedisLock.class);
private static StringRedisTemplate redisTemplate;
/**
* 分布式鎖的鍵值
*/
String lockKey; //鎖的鍵值
int expireMsecs = 10 * 1000; //鎖超時,防止線程在入鎖以后,無限的執(zhí)行等待
int timeoutMsecs = 10 * 1000; //鎖等待,防止線程饑餓
boolean locked = false; //是否已經(jīng)獲取鎖
/**
* 獲取指定鍵值的鎖
* @param lockKey 鎖的鍵值
*/
public JedisLock(String lockKey) {
this.lockKey = lockKey;
}
/**
* 獲取指定鍵值的鎖,同時設(shè)置獲取鎖超時時間
* @param lockKey 鎖的鍵值
* @param timeoutMsecs 獲取鎖超時時間
*/
public JedisLock(String lockKey, int timeoutMsecs) {
this.lockKey = lockKey;
this.timeoutMsecs = timeoutMsecs;
}
/**
* 獲取指定鍵值的鎖,同時設(shè)置獲取鎖超時時間和鎖過期時間
* @param lockKey 鎖的鍵值
* @param timeoutMsecs 獲取鎖超時時間
* @param expireMsecs 鎖失效時間
*/
public JedisLock(String lockKey, int timeoutMsecs, int expireMsecs) {
this.lockKey = lockKey;
this.timeoutMsecs = timeoutMsecs;
this.expireMsecs = expireMsecs;
}
public String getLockKey() {
return lockKey;
}
/**
*
* @return true if lock is acquired, false acquire timeouted
* @throws InterruptedException
* in case of thread interruption
*/
public synchronized boolean acquire() {
int timeout = timeoutMsecs;
if(redisTemplate == null){
redisTemplate = SpringContextUtil.getBean(StringRedisTemplate.class);
}
try {
while (timeout >= 0) {
long expires = System.currentTimeMillis() + expireMsecs + 1;
String expiresStr = String.valueOf(expires); //鎖到期時間
if (redisTemplate.opsForValue().setIfAbsent(lockKey, expiresStr)) {
// lock acquired
locked = true;
return true;
}
String currentValueStr = redisTemplate.opsForValue().get(lockKey); //redis里的時間
if (currentValueStr != null && Long.parseLong(currentValueStr) < System.currentTimeMillis()) {
//判斷是否為空,不為空的情況下,如果被其他線程設(shè)置了值,則第二個條件判斷是過不去的
// lock is expired
String oldValueStr = redisTemplate.opsForValue().getAndSet(lockKey, expiresStr);
//獲取上一個鎖到期時間,并設(shè)置現(xiàn)在的鎖到期時間,
//只有一個線程才能獲取上一個線上的設(shè)置時間,因為jedis.getSet是同步的
if (oldValueStr != null && oldValueStr.equals(currentValueStr)) {
//如過這個時候,多個線程恰好都到了這里,但是只有一個線程的設(shè)置值和當(dāng)前值相同,他才有權(quán)利獲取鎖
// lock acquired
locked = true;
return true;
}
}
timeout -= 100;
Thread.sleep(100);
}
} catch (Exception e) {
logger.error("release lock due to error",e);
}
return false;
}
/**
* 釋放鎖
*/
public synchronized void release() {
if(redisTemplate == null){
redisTemplate = SpringContextUtil.getBean(StringRedisTemplate.class);
}
try {
if (locked) {
String currentValueStr = redisTemplate.opsForValue().get(lockKey); //redis里的時間
//校驗是否超過有效期,如果不在有效期內(nèi),那說明當(dāng)前鎖已經(jīng)失效,不能進行刪除鎖操作
if (currentValueStr != null && Long.parseLong(currentValueStr) > System.currentTimeMillis()) {
redisTemplate.delete(lockKey);
locked = false;
}
}
} catch (Exception e) {
logger.error("release lock due to error",e);
}
}
}
DistributedLockUtil
public class DistributedLockUtil{
/**
* 獲取分布式鎖
* 默認(rèn)獲取鎖10s超時,鎖過期時間60s
* @author yangwenkui
* @time 2016年5月6日 下午1:30:46
* @return
*/
public static DistributedLock getDistributedLock(String lockKey){
lockKey = assembleKey(lockKey);
JedisLock lock = new JedisLock(lockKey);
return lock;
}
/**
* 正式環(huán)境、測試環(huán)境共用一個redis時,避免key相同造成影響
* @author yangwenkui
* @param lockKey
* @return
*/
private static String assembleKey(String lockKey) {
return String.format("lock_%s",lockKey );
}
/**
* 獲取分布式鎖
* 默認(rèn)獲取鎖10s超時,鎖過期時間60s
* @author yangwenkui
* @time 2016年5月6日 下午1:38:32
* @param lockKey
* @param timeoutMsecs 指定獲取鎖超時時間
* @return
*/
public static DistributedLock getDistributedLock(String lockKey,int timeoutMsecs){
lockKey = assembleKey(lockKey);
JedisLock lock = new JedisLock(lockKey,timeoutMsecs);
return lock;
}
/**
* 獲取分布式鎖
* 默認(rèn)獲取鎖10s超時,鎖過期時間60s
* @author yangwenkui
* @time 2016年5月6日 下午1:40:04
* @param lockKey 鎖的key
* @param timeoutMsecs 指定獲取鎖超時時間
* @param expireMsecs 指定鎖過期時間
* @return
*/
public static DistributedLock getDistributedLock(String lockKey,int timeoutMsecs,int expireMsecs){
lockKey = assembleKey(lockKey);
JedisLock lock = new JedisLock(lockKey,expireMsecs,timeoutMsecs);
return lock;
}
}
使用示例
DistributedLock lock = DistributedLockUtil.getDistributedLock(key);
try {
if (lock.acquire()) {
//獲取鎖成功業(yè)務(wù)代碼
} else { // 獲取鎖失敗
//獲取鎖失敗業(yè)務(wù)代碼
} finally {
if (lock != null) {
lock.release();
}
}
實現(xiàn)原理簡析
主要是依賴redis的setnx和getset命令對時間進行操作,從而實現(xiàn)鎖的功能。以下兩個文章對分布式鎖進行了極其明細(xì)的分析,會讓你對分布式鎖的認(rèn)識更加清晰。
《基于Redis的分布式鎖到底安全嗎(上)?》
《基于Redis的分布式鎖到底安全嗎(下)?》
注意事項
- 基于redis的分布式鎖依賴于系統(tǒng)時鐘,需要保證各個競爭者的時鐘的一致性,否則會出現(xiàn)一個參與者獲得鎖,而另一個參與者的時鐘判斷其已過期,導(dǎo)致分布式鎖失效;
- 需要保證redis節(jié)點的高可用,建議使用哨兵機制;
- 在使用分布式鎖之前,考慮是否可以通過樂觀鎖或無鎖解決并發(fā)同步問題,畢竟使用鎖的代價很是比較高昂的;
本人搭建好的spring boot web后端開發(fā)框架已上傳至GitHub,歡迎吐槽!
https://github.com/q7322068/rest-base,已用于多個正式項目,當(dāng)前可能因為版本問題不是很完善,后續(xù)持續(xù)優(yōu)化,希望你能有所收獲!