redis分布式鎖RedissonLock的實(shí)現(xiàn)細(xì)節(jié)解析
redis分布式鎖RedissonLock
簡(jiǎn)單使用
String key = "key-lock";
RLock lock = redisson.getLock(key);
lock.lock();
try {
// TODO
} catch (Exception e){
log.error(e.getMessage(), e);
} finally {
lock.unlock();
}
String key = "key-tryLock";
long maxWaitTime = 3_000;
RLock lock = redisson.getLock(key);
if (lock.tryLock(maxWaitTime, TimeUnit.MILLISECONDS)){
try {
// TODO
} catch (Exception e){
log.error(e.getMessage(), e);
} finally {
lock.unlock();
}
} else {
log.debug("redis鎖競(jìng)爭(zhēng)失敗");
}
流程圖
多個(gè)線程節(jié)點(diǎn)鎖競(jìng)爭(zhēng)的正常流程如下圖:

多個(gè)線程節(jié)點(diǎn)鎖競(jìng)爭(zhēng),并出現(xiàn)節(jié)點(diǎn)下線的異常流程如下圖:

源碼解析
RedissonLock是可重入鎖,使用redis的hash結(jié)構(gòu)作為鎖的標(biāo)識(shí)存儲(chǔ),鎖的名稱作為hash的key,UUID + 線程ID作為hash的field,鎖被重入的次數(shù)作為hash的value。如圖所示:

private void lock(long leaseTime, TimeUnit unit, boolean interruptibly) throws InterruptedException {
long threadId = Thread.currentThread().getId();
// 嘗試獲取鎖,鎖獲取成功則ttl為null;獲取失敗則返回鎖的剩余過期時(shí)間
Long ttl = tryAcquire(leaseTime, unit, threadId);
if (ttl == null) {
return;
}
// 鎖被其他線程占用而索取失敗,使用線程通知而非自旋的方式等待鎖
// 使用redis的發(fā)布訂閱pub/sub功能來(lái)等待鎖的釋放通知
RFuture<RedissonLockEntry> future = subscribe(threadId);
commandExecutor.syncSubscription(future);
try {
while (true) {
ttl = tryAcquire(leaseTime, unit, threadId);
// 嘗試獲取鎖,鎖獲取成功則ttl為null;獲取失敗則返回鎖的剩余過期時(shí)間
if (ttl == null) {
break;
}
if (ttl >= 0) {
// 使用LockSupport.parkNanos方法線程休眠
try {
getEntry(threadId).getLatch().tryAcquire(ttl, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
if (interruptibly) {
throw e;
}
getEntry(threadId).getLatch().tryAcquire(ttl, TimeUnit.MILLISECONDS);
}
} else {
if (interruptibly) {
getEntry(threadId).getLatch().acquire();
} else {
getEntry(threadId).getLatch().acquireUninterruptibly();
}
}
}
} finally {
// 退出鎖競(jìng)爭(zhēng)(鎖獲取成功或者放棄獲取鎖),則取消鎖的釋放訂閱
unsubscribe(future, threadId);
}
}
public boolean tryLock(long waitTime, long leaseTime, TimeUnit unit) throws InterruptedException {
long time = unit.toMillis(waitTime);
long current = System.currentTimeMillis();
long threadId = Thread.currentThread().getId();
Long ttl = tryAcquire(leaseTime, unit, threadId);
if (ttl == null) {
return true;
}
time -= System.currentTimeMillis() - current;
if (time <= 0) {
acquireFailed(threadId);
return false;
}
current = System.currentTimeMillis();
RFuture<RedissonLockEntry> subscribeFuture = subscribe(threadId);
if (!await(subscribeFuture, time, TimeUnit.MILLISECONDS)) {
if (!subscribeFuture.cancel(false)) {
subscribeFuture.onComplete((res, e) -> {
if (e == null) {
unsubscribe(subscribeFuture, threadId);
}
});
}
acquireFailed(threadId);
return false;
}
try {
time -= System.currentTimeMillis() - current;
if (time <= 0) {
acquireFailed(threadId);
return false;
}
while (true) {
long currentTime = System.currentTimeMillis();
ttl = tryAcquire(leaseTime, unit, threadId);
// lock acquired
if (ttl == null) {
return true;
}
time -= System.currentTimeMillis() - currentTime;
if (time <= 0) {
acquireFailed(threadId);
return false;
}
currentTime = System.currentTimeMillis();
if (ttl >= 0 && ttl < time) {
getEntry(threadId).getLatch().tryAcquire(ttl, TimeUnit.MILLISECONDS);
} else {
getEntry(threadId).getLatch().tryAcquire(time, TimeUnit.MILLISECONDS);
}
time -= System.currentTimeMillis() - currentTime;
if (time <= 0) {
acquireFailed(threadId);
return false;
}
}
} finally {
unsubscribe(subscribeFuture, threadId);
}
}
RedissonLock實(shí)現(xiàn)的是可重入鎖,通過redis的hash結(jié)構(gòu)實(shí)現(xiàn),而非加單的set nx ex。為了實(shí)現(xiàn)原子性的復(fù)雜的加鎖邏輯,而通過lua腳本實(shí)現(xiàn)。獲取鎖會(huì)有如下三種狀態(tài):
1、鎖未被任何線程占用,則鎖獲取成功,返回null
2、鎖被當(dāng)前線程占用,則鎖獲取成功并進(jìn)行鎖的重入,對(duì)鎖的重入計(jì)數(shù)+1,返回null
3、鎖被其他線程占用,則鎖獲取失敗,返回該鎖的自動(dòng)過期時(shí)間ttl
<T> RFuture<T> tryLockInnerAsync(long leaseTime, TimeUnit unit, long threadId, RedisStrictCommand<T> command) {
internalLockLeaseTime = unit.toMillis(leaseTime);
return commandExecutor.evalWriteAsync(getName(), LongCodec.INSTANCE, command,
"if (redis.call('exists', KEYS[1]) == 0) then " +
"redis.call('hset', KEYS[1], ARGV[2], 1); " +
"redis.call('pexpire', KEYS[1], ARGV[1]); " +
"return nil; " +
"end; " +
"if (redis.call('hexists', KEYS[1], ARGV[2]) == 1) then " +
"redis.call('hincrby', KEYS[1], ARGV[2], 1); " +
"redis.call('pexpire', KEYS[1], ARGV[1]); " +
"return nil; " +
"end; " +
"return redis.call('pttl', KEYS[1]);",
Collections.<Object>singletonList(getName()), internalLockLeaseTime, getLockName(threadId));
}
當(dāng)鎖因?yàn)楸黄渌€程占用而 使用redis的發(fā)布訂閱pub/sub功能,通過監(jiān)聽鎖的釋放通知(在其他線程通過RedissonLock釋放鎖時(shí),會(huì)通過發(fā)布訂閱pub/sub功能發(fā)起通知),等待鎖被其他線程釋放。通過如此的線程喚醒而非自旋的操作,提高了鎖的效率。
public RFuture<E> subscribe(String entryName, String channelName) {
AtomicReference<Runnable> listenerHolder = new AtomicReference<Runnable>();
AsyncSemaphore semaphore = service.getSemaphore(new ChannelName(channelName));
RPromise<E> newPromise = new RedissonPromise<E>() {
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return semaphore.remove(listenerHolder.get());
}
};
Runnable listener = new Runnable() {
@Override
public void run() {
E entry = entries.get(entryName);
if (entry != null) {
entry.aquire();
semaphore.release();
entry.getPromise().onComplete(new TransferListener<E>(newPromise));
return;
}
E value = createEntry(newPromise);
value.aquire();
E oldValue = entries.putIfAbsent(entryName, value);
if (oldValue != null) {
oldValue.aquire();
semaphore.release();
oldValue.getPromise().onComplete(new TransferListener<E>(newPromise));
return;
}
RedisPubSubListener<Object> listener = createListener(channelName, value);
service.subscribe(LongCodec.INSTANCE, channelName, semaphore, listener);
}
};
semaphore.acquire(listener);
listenerHolder.set(listener);
return newPromise;
}
由于是可重入鎖則需要在釋放鎖的時(shí)候做訂閱通知,因此釋放鎖的操作同樣是lua腳本實(shí)現(xiàn)。鎖的釋放會(huì)有如下三個(gè)狀態(tài):
1、等待釋放的鎖不存在或者不是當(dāng)前線程持有,返回null
2、等待釋放的鎖被當(dāng)前線程持有,且該鎖當(dāng)前被重入多次,則鎖的重入計(jì)數(shù)-1,返回0
3、等待釋放的鎖被當(dāng)前線程持有,且該鎖當(dāng)前未被重入,則鎖的刪除并發(fā)布該鎖釋放的訂閱通知,返回1
protected RFuture<Boolean> unlockInnerAsync(long threadId) {
return commandExecutor.evalWriteAsync(getName(), LongCodec.INSTANCE, RedisCommands.EVAL_BOOLEAN,
"if (redis.call('hexists', KEYS[1], ARGV[3]) == 0) then " +
"return nil;" +
"end; " +
"local counter = redis.call('hincrby', KEYS[1], ARGV[3], -1); " +
"if (counter > 0) then " +
"redis.call('pexpire', KEYS[1], ARGV[2]); " +
"return 0; " +
"else " +
"redis.call('del', KEYS[1]); " +
"redis.call('publish', KEYS[2], ARGV[1]); " +
"return 1; "+
"end; " +
"return nil;",
Arrays.<Object>asList(getName(), getChannelName()), LockPubSub.UNLOCK_MESSAGE, internalLockLeaseTime, getLockName(threadId));
}
Watchdog
RedissonLock為了避免應(yīng)用獲取鎖后宕機(jī),因?yàn)闆]人來(lái)釋放鎖而導(dǎo)致死鎖情況的出現(xiàn),默認(rèn)每次鎖的占用只有30秒的時(shí)間(org.redisson.config.Config#lockWatchdogTimeout = 30 * 1000)。
于是便有了Watchdog設(shè)計(jì),由獨(dú)立的線程定時(shí)給未釋放的鎖續(xù)期,默認(rèn)鎖有效期的三分之一的時(shí)長(zhǎng)即每10秒給鎖自動(dòng)續(xù)期。
private void renewExpiration() {
ExpirationEntry ee = EXPIRATION_RENEWAL_MAP.get(getEntryName());
if (ee == null) {
return;
}
// 默認(rèn)10秒鐘后執(zhí)行鎖續(xù)期任務(wù)
Timeout task = commandExecutor.getConnectionManager().newTimeout(new TimerTask() {
@Override
public void run(Timeout timeout) throws Exception {
ExpirationEntry ent = EXPIRATION_RENEWAL_MAP.get(getEntryName());
if (ent == null) {
return;
}
Long threadId = ent.getFirstThreadId();
if (threadId == null) {
return;
}
RFuture<Boolean> future = renewExpirationAsync(threadId);
future.onComplete((res, e) -> {
if (e != null) {
log.error("Can't update lock " + getName() + " expiration", e);
return;
}
// 如果鎖續(xù)期成功,則10秒鐘后再次續(xù)期
if (res) {
renewExpiration();
}
});
}
}, internalLockLeaseTime / 3, TimeUnit.MILLISECONDS);
ee.setTimeout(task);
}
protected RFuture<Boolean> renewExpirationAsync(long threadId) {
return commandExecutor.evalWriteAsync(getName(), LongCodec.INSTANCE, RedisCommands.EVAL_BOOLEAN,
"if (redis.call('hexists', KEYS[1], ARGV[2]) == 1) then " +
"redis.call('pexpire', KEYS[1], ARGV[1]); " +
"return 1; " +
"end; " +
"return 0;",
Collections.<Object>singletonList(getName()),
internalLockLeaseTime, getLockName(threadId));
}
Redisson 幾種鎖
1. 可重入鎖(Reentrant Lock)
Redisson的分布式可重入鎖RLock Java對(duì)象實(shí)現(xiàn)了java.util.concurrent.locks.Lock接口,同時(shí)還支持自動(dòng)過期解鎖。
public void testReentrantLock(RedissonClient redisson){
RLock lock = redisson.getLock("anyLock");
try{
// 1. 最常見的使用方法
//lock.lock();
// 2. 支持過期解鎖功能,10秒鐘以后自動(dòng)解鎖, 無(wú)需調(diào)用unlock方法手動(dòng)解鎖
//lock.lock(10, TimeUnit.SECONDS);
// 3. 嘗試加鎖,最多等待3秒,上鎖以后10秒自動(dòng)解鎖
boolean res = lock.tryLock(3, 10, TimeUnit.SECONDS);
if(res){ //成功
// do your business
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
Redisson同時(shí)還為分布式鎖提供了異步執(zhí)行的相關(guān)方法:
public void testAsyncReentrantLock(RedissonClient redisson){
RLock lock = redisson.getLock("anyLock");
try{
lock.lockAsync();
lock.lockAsync(10, TimeUnit.SECONDS);
Future<Boolean> res = lock.tryLockAsync(3, 10, TimeUnit.SECONDS);
if(res.get()){
// do your business
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
2. 公平鎖(Fair Lock)
Redisson分布式可重入公平鎖也是實(shí)現(xiàn)了java.util.concurrent.locks.Lock接口的一種RLock對(duì)象。在提供了自動(dòng)過期解鎖功能的同時(shí),保證了當(dāng)多個(gè)Redisson客戶端線程同時(shí)請(qǐng)求加鎖時(shí),優(yōu)先分配給先發(fā)出請(qǐng)求的線程。
public void testFairLock(RedissonClient redisson){
RLock fairLock = redisson.getFairLock("anyLock");
try{
// 最常見的使用方法
fairLock.lock();
// 支持過期解鎖功能, 10秒鐘以后自動(dòng)解鎖,無(wú)需調(diào)用unlock方法手動(dòng)解鎖
fairLock.lock(10, TimeUnit.SECONDS);
// 嘗試加鎖,最多等待100秒,上鎖以后10秒自動(dòng)解鎖
boolean res = fairLock.tryLock(100, 10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
fairLock.unlock();
}
}
Redisson同時(shí)還為分布式可重入公平鎖提供了異步執(zhí)行的相關(guān)方法:
RLock fairLock = redisson.getFairLock("anyLock");
fairLock.lockAsync();
fairLock.lockAsync(10, TimeUnit.SECONDS);
Future<Boolean> res = fairLock.tryLockAsync(100, 10, TimeUnit.SECONDS);
3. 聯(lián)鎖(MultiLock)
Redisson的RedissonMultiLock對(duì)象可以將多個(gè)RLock對(duì)象關(guān)聯(lián)為一個(gè)聯(lián)鎖,每個(gè)RLock對(duì)象實(shí)例可以來(lái)自于不同的Redisson實(shí)例。
public void testMultiLock(RedissonClient redisson1,
RedissonClient redisson2, RedissonClient redisson3){
RLock lock1 = redisson1.getLock("lock1");
RLock lock2 = redisson2.getLock("lock2");
RLock lock3 = redisson3.getLock("lock3");
RedissonMultiLock lock = new RedissonMultiLock(lock1, lock2, lock3);
try {
// 同時(shí)加鎖:lock1 lock2 lock3, 所有的鎖都上鎖成功才算成功。
lock.lock();
// 嘗試加鎖,最多等待100秒,上鎖以后10秒自動(dòng)解鎖
boolean res = lock.tryLock(100, 10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
4. 紅鎖(RedLock)
Redisson的RedissonRedLock對(duì)象實(shí)現(xiàn)了Redlock介紹的加鎖算法。該對(duì)象也可以用來(lái)將多個(gè)RLock
對(duì)象關(guān)聯(lián)為一個(gè)紅鎖,每個(gè)RLock對(duì)象實(shí)例可以來(lái)自于不同的Redisson實(shí)例。
public void testRedLock(RedissonClient redisson1,
RedissonClient redisson2, RedissonClient redisson3){
RLock lock1 = redisson1.getLock("lock1");
RLock lock2 = redisson2.getLock("lock2");
RLock lock3 = redisson3.getLock("lock3");
RedissonRedLock lock = new RedissonRedLock(lock1, lock2, lock3);
try {
// 同時(shí)加鎖:lock1 lock2 lock3, 紅鎖在大部分節(jié)點(diǎn)上加鎖成功就算成功。
lock.lock();
// 嘗試加鎖,最多等待100秒,上鎖以后10秒自動(dòng)解鎖
boolean res = lock.tryLock(100, 10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
5. 讀寫鎖(ReadWriteLock)
Redisson的分布式可重入讀寫鎖RReadWriteLock Java對(duì)象實(shí)現(xiàn)了java.util.concurrent.locks.ReadWriteLock接口。同時(shí)還支持自動(dòng)過期解鎖。該對(duì)象允許同時(shí)有多個(gè)讀取鎖,但是最多只能有一個(gè)寫入鎖。
RReadWriteLock rwlock = redisson.getLock("anyRWLock");
// 最常見的使用方法
rwlock.readLock().lock();
// 或
rwlock.writeLock().lock();
// 支持過期解鎖功能
// 10秒鐘以后自動(dòng)解鎖
// 無(wú)需調(diào)用unlock方法手動(dòng)解鎖
rwlock.readLock().lock(10, TimeUnit.SECONDS);
// 或
rwlock.writeLock().lock(10, TimeUnit.SECONDS);
// 嘗試加鎖,最多等待100秒,上鎖以后10秒自動(dòng)解鎖
boolean res = rwlock.readLock().tryLock(100, 10, TimeUnit.SECONDS);
// 或
boolean res = rwlock.writeLock().tryLock(100, 10, TimeUnit.SECONDS);
...
lock.unlock();
6. 信號(hào)量(Semaphore)
Redisson的分布式信號(hào)量(Semaphore)Java對(duì)象RSemaphore采用了與java.util.concurrent.Semaphore相似的接口和用法。
RSemaphore semaphore = redisson.getSemaphore("semaphore");
semaphore.acquire();
//或
semaphore.acquireAsync();
semaphore.acquire(23);
semaphore.tryAcquire();
//或
semaphore.tryAcquireAsync();
semaphore.tryAcquire(23, TimeUnit.SECONDS);
//或
semaphore.tryAcquireAsync(23, TimeUnit.SECONDS);
semaphore.release(10);
semaphore.release();
//或
semaphore.releaseAsync();
7. 可過期性信號(hào)量(PermitExpirableSemaphore)
Redisson的可過期性信號(hào)量(PermitExpirableSemaphore)實(shí)在RSemaphore對(duì)象的基礎(chǔ)上,為每個(gè)信號(hào)增加了一個(gè)過期時(shí)間。每個(gè)信號(hào)可以通過獨(dú)立的ID來(lái)辨識(shí),釋放時(shí)只能通過提交這個(gè)ID才能釋放。
RPermitExpirableSemaphore semaphore = redisson.getPermitExpirableSemaphore("mySemaphore");
String permitId = semaphore.acquire();
// 獲取一個(gè)信號(hào),有效期只有2秒鐘。
String permitId = semaphore.acquire(2, TimeUnit.SECONDS);
// ...
semaphore.release(permitId);
8. 閉鎖(CountDownLatch)
Redisson的分布式閉鎖(CountDownLatch)Java對(duì)象RCountDownLatch采用了與java.util.concurrent.CountDownLatch相似的接口和用法。
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- Redis:Redisson分布式鎖的使用方式(推薦使用)
- Java使用Redisson分布式鎖實(shí)現(xiàn)原理
- redis和redisson實(shí)現(xiàn)分布式鎖的操作方法
- Redisson如何解決redis分布式鎖過期時(shí)間到了業(yè)務(wù)沒執(zhí)行完問題
- Java redisson實(shí)現(xiàn)分布式鎖原理詳解
- Redisson如何解決Redis分布式鎖提前釋放問題
- Redis集群利用Redisson實(shí)現(xiàn)分布式鎖方式
- 基于Redis分布式鎖Redisson及SpringBoot集成Redisson
- redisson分布式鎖的用法大全
- Java實(shí)現(xiàn)Redisson分布式鎖的10大陷阱與避坑指南
相關(guān)文章
詳解如何在低版本的Spring中快速實(shí)現(xiàn)類似自動(dòng)配置的功能
這篇文章主要介紹了詳解如何在低版本的Spring中快速實(shí)現(xiàn)類似自動(dòng)配置的功能,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來(lái)看看吧2019-05-05
java中Map如何根據(jù)key的大小進(jìn)行排序詳解
這篇文章主要給大家介紹了關(guān)于java中Map如何根據(jù)key的大小進(jìn)行排序的相關(guān)資料,有時(shí)候我們業(yè)務(wù)上需要對(duì)map里面的值按照key的大小來(lái)進(jìn)行排序的時(shí)候我們就可以利用如下方法來(lái)進(jìn)行排序了,需要的朋友可以參考下2023-09-09
詳解SpringBoot如何優(yōu)雅的進(jìn)行前后端通信
現(xiàn)在的項(xiàng)目基本上都是前后端分離的項(xiàng)目,如何打通前后端,接收前端傳過來(lái)的參數(shù)呢,下面小編就來(lái)和大家詳細(xì)介紹一下SpringBoot如何優(yōu)雅的進(jìn)行前后端通信2024-03-03
Java class文件格式之訪問標(biāo)志信息_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
access_flags 描述的是當(dāng)前類(或者接口)的訪問修飾符, 如public, private等, 此外, 這里面還存在一個(gè)標(biāo)志位, 標(biāo)志當(dāng)前的額這個(gè)class描述的是類, 還是接口2017-06-06

