SpringBoot利用注解來(lái)實(shí)現(xiàn)Redis分布式鎖
一、業(yè)務(wù)背景
有些業(yè)務(wù)請(qǐng)求,屬于耗時(shí)操作,需要加鎖,防止后續(xù)的并發(fā)操作,同時(shí)對(duì)數(shù)據(jù)庫(kù)的數(shù)據(jù)進(jìn)行操作,需要避免對(duì)之前的業(yè)務(wù)造成影響。
二、分析流程
使用 Redis 作為分布式鎖,將鎖的狀態(tài)放到 Redis 統(tǒng)一維護(hù),解決集群中單機(jī) JVM 信息不互通的問(wèn)題,規(guī)定操作順序,保護(hù)用戶的數(shù)據(jù)正確。
梳理設(shè)計(jì)流程
- 新建注解 @interface,在注解里設(shè)定入?yún)?biāo)志
- 增加 AOP 切點(diǎn),掃描特定注解
- 建立 @Aspect 切面任務(wù),注冊(cè) bean 和攔截特定方法
- 特定方法參數(shù) ProceedingJoinPoint,對(duì)方法 pjp.proceed() 前后進(jìn)行攔截
- 切點(diǎn)前進(jìn)行加鎖,任務(wù)執(zhí)行后進(jìn)行刪除 key
核心步驟:加鎖、解鎖和續(xù)時(shí)
加鎖
使用了 RedisTemplate 的 opsForValue.setIfAbsent 方法,判斷是否有 key,設(shè)定一個(gè)隨機(jī)數(shù) UUID.random().toString,生成一個(gè)隨機(jī)數(shù)作為 value。
從 redis 中獲取鎖之后,對(duì) key 設(shè)定 expire 失效時(shí)間,到期后自動(dòng)釋放鎖。
按照這種設(shè)計(jì),只有第一個(gè)成功設(shè)定 Key 的請(qǐng)求,才能進(jìn)行后續(xù)的數(shù)據(jù)操作,后續(xù)其它請(qǐng)求由于無(wú)法獲得資源,將會(huì)失敗結(jié)束。
超時(shí)問(wèn)題
擔(dān)心 pjp.proceed() 切點(diǎn)執(zhí)行的方法太耗時(shí),導(dǎo)致 Redis 中的 key 由于超時(shí)提前釋放了。
例如,線程 A 先獲取鎖,proceed 方法耗時(shí),超過(guò)了鎖超時(shí)時(shí)間,到期釋放了鎖,這時(shí)另一個(gè)線程 B 成功獲取 Redis 鎖,兩個(gè)線程同時(shí)對(duì)同一批數(shù)據(jù)進(jìn)行操作,導(dǎo)致數(shù)據(jù)不準(zhǔn)確。
解決方案:增加一個(gè)「續(xù)時(shí)」
任務(wù)不完成,鎖不釋放:
維護(hù)了一個(gè)定時(shí)線程池 ScheduledExecutorService,每隔 2s 去掃描加入隊(duì)列中的 Task,判斷是否失效時(shí)間是否快到了,公式為:【失效時(shí)間】<= 【當(dāng)前時(shí)間】+【失效間隔(三分之一超時(shí))】
/**
?*?線程池,每個(gè)?JVM?使用一個(gè)線程去維護(hù)?keyAliveTime,定時(shí)執(zhí)行?runnable
?*/
private?static?final?ScheduledExecutorService?SCHEDULER?=?
new?ScheduledThreadPoolExecutor(1,?
new?BasicThreadFactory.Builder().namingPattern("redisLock-schedule-pool").daemon(true).build());
static?{
????SCHEDULER.scheduleAtFixedRate(()?->?{
????????//?do?something?to?extend?time
????},?0,??2,?TimeUnit.SECONDS);
}
三、設(shè)計(jì)方案
經(jīng)過(guò)上面的分析,同事設(shè)計(jì)出了這個(gè)方案:

前面已經(jīng)說(shuō)了整體流程,這里強(qiáng)調(diào)一下幾個(gè)核心步驟:
- 攔截注解 @RedisLock,獲取必要的參數(shù)
- 加鎖操作
- 續(xù)時(shí)操作
- 結(jié)束業(yè)務(wù),釋放鎖
四、實(shí)操
之前也有整理過(guò) AOP 使用方法,可以參考一下
相關(guān)屬性類配置
業(yè)務(wù)屬性枚舉設(shè)定
public?enum?RedisLockTypeEnum?{
????/**
?????*?自定義?key?前綴
?????*/
????ONE("Business1",?"Test1"),
????
????TWO("Business2",?"Test2");
????private?String?code;
????private?String?desc;
????RedisLockTypeEnum(String?code,?String?desc)?{
????????this.code?=?code;
????????this.desc?=?desc;
????}
????public?String?getCode()?{
????????return?code;
????}
????public?String?getDesc()?{
????????return?desc;
????}
????public?String?getUniqueKey(String?key)?{
????????return?String.format("%s:%s",?this.getCode(),?key);
????}
}
任務(wù)隊(duì)列保存參數(shù)
public?class?RedisLockDefinitionHolder?{
????/**
?????*?業(yè)務(wù)唯一?key
?????*/
????private?String?businessKey;
????/**
?????*?加鎖時(shí)間?(秒?s)
?????*/
????private?Long?lockTime;
????/**
?????*?上次更新時(shí)間(ms)
?????*/
????private?Long?lastModifyTime;
????/**
?????*?保存當(dāng)前線程
?????*/
????private?Thread?currentTread;
????/**
?????*?總共嘗試次數(shù)
?????*/
????private?int?tryCount;
????/**
?????*?當(dāng)前嘗試次數(shù)
?????*/
????private?int?currentCount;
????/**
?????*?更新的時(shí)間周期(毫秒),公式?=?加鎖時(shí)間(轉(zhuǎn)成毫秒)?/?3
?????*/
????private?Long?modifyPeriod;
????public?RedisLockDefinitionHolder(String?businessKey,?Long?lockTime,?Long?lastModifyTime,?Thread?currentTread,?int?tryCount)?{
????????this.businessKey?=?businessKey;
????????this.lockTime?=?lockTime;
????????this.lastModifyTime?=?lastModifyTime;
????????this.currentTread?=?currentTread;
????????this.tryCount?=?tryCount;
????????this.modifyPeriod?=?lockTime?*?1000?/?3;
????}
}
設(shè)定被攔截的注解名字
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,?ElementType.TYPE})
public?@interface?RedisLockAnnotation?{
????/**
?????*?特定參數(shù)識(shí)別,默認(rèn)取第?0?個(gè)下標(biāo)
?????*/
????int?lockFiled()?default?0;
????/**
?????*?超時(shí)重試次數(shù)
?????*/
????int?tryCount()?default?3;
????/**
?????*?自定義加鎖類型
?????*/
????RedisLockTypeEnum?typeEnum();
????/**
?????*?釋放時(shí)間,秒?s?單位
?????*/
????long?lockTime()?default?30;
}
核心切面攔截的操作
RedisLockAspect.java 該類分成三部分來(lái)描述具體作用
Pointcut 設(shè)定
/**
?*?@annotation?中的路徑表示攔截特定注解
?*/
@Pointcut("@annotation(cn.sevenyuan.demo.aop.lock.RedisLockAnnotation)")
public?void?redisLockPC()?{
}
Around 前后進(jìn)行加鎖和釋放鎖
前面步驟定義了我們想要攔截的切點(diǎn),下一步就是在切點(diǎn)前后做一些自定義操作:
@Around(value?=?"redisLockPC()")
public?Object?around(ProceedingJoinPoint?pjp)?throws?Throwable?{
????//?解析參數(shù)
????Method?method?=?resolveMethod(pjp);
????RedisLockAnnotation?annotation?=?method.getAnnotation(RedisLockAnnotation.class);
????RedisLockTypeEnum?typeEnum?=?annotation.typeEnum();
????Object[]?params?=?pjp.getArgs();
????String?ukString?=?params[annotation.lockFiled()].toString();
????//?省略很多參數(shù)校驗(yàn)和判空
????String?businessKey?=?typeEnum.getUniqueKey(ukString);
????String?uniqueValue?=?UUID.randomUUID().toString();
????//?加鎖
????Object?result?=?null;
????try?{
????????boolean?isSuccess?=?redisTemplate.opsForValue().setIfAbsent(businessKey,?uniqueValue);
????????if?(!isSuccess)?{
????????????throw?new?Exception("You?can't?do?it,because?another?has?get?the?lock?=-=");
????????}
????????redisTemplate.expire(businessKey,?annotation.lockTime(),?TimeUnit.SECONDS);
????????Thread?currentThread?=?Thread.currentThread();
????????//?將本次?Task?信息加入「延時(shí)」隊(duì)列中
????????holderList.add(new?RedisLockDefinitionHolder(businessKey,?annotation.lockTime(),?System.currentTimeMillis(),
????????????????currentThread,?annotation.tryCount()));
????????//?執(zhí)行業(yè)務(wù)操作
????????result?=?pjp.proceed();
????????//?線程被中斷,拋出異常,中斷此次請(qǐng)求
????????if?(currentThread.isInterrupted())?{
????????????throw?new?InterruptedException("You?had?been?interrupted?=-=");
????????}
????}?catch?(InterruptedException?e?)?{
????????log.error("Interrupt?exception,?rollback?transaction",?e);
????????throw?new?Exception("Interrupt?exception,?please?send?request?again");
????}?catch?(Exception?e)?{
????????log.error("has?some?error,?please?check?again",?e);
????}?finally?{
????????//?請(qǐng)求結(jié)束后,強(qiáng)制刪掉?key,釋放鎖
????????redisTemplate.delete(businessKey);
????????log.info("release?the?lock,?businessKey?is?["?+?businessKey?+?"]");
????}
????return?result;
}
上述流程簡(jiǎn)單總結(jié)一下:
- 解析注解參數(shù),獲取注解值和方法上的參數(shù)值
- redis 加鎖并且設(shè)置超時(shí)時(shí)間
- 將本次 Task 信息加入「延時(shí)」隊(duì)列中,進(jìn)行續(xù)時(shí),方式提前釋放鎖
- 加了一個(gè)線程中斷標(biāo)志
- 結(jié)束請(qǐng)求,finally 中釋放鎖
續(xù)時(shí)操作
這里用了 ScheduledExecutorService,維護(hù)了一個(gè)線程,不斷對(duì)任務(wù)隊(duì)列中的任務(wù)進(jìn)行判斷和延長(zhǎng)超時(shí)時(shí)間:
//?掃描的任務(wù)隊(duì)列
private?static?ConcurrentLinkedQueue<RedisLockDefinitionHolder>?holderList?=?new?ConcurrentLinkedQueue();
/**
?*?線程池,維護(hù)keyAliveTime
?*/
private?static?final?ScheduledExecutorService?SCHEDULER?=?new?ScheduledThreadPoolExecutor(1,
????????new?BasicThreadFactory.Builder().namingPattern("redisLock-schedule-pool").daemon(true).build());
{
????//?兩秒執(zhí)行一次「續(xù)時(shí)」操作
????SCHEDULER.scheduleAtFixedRate(()?->?{
????????//?這里記得加?try-catch,否者報(bào)錯(cuò)后定時(shí)任務(wù)將不會(huì)再執(zhí)行=-=
????????Iterator<RedisLockDefinitionHolder>?iterator?=?holderList.iterator();
????????while?(iterator.hasNext())?{
????????????RedisLockDefinitionHolder?holder?=?iterator.next();
????????????//?判空
????????????if?(holder?==?null)?{
????????????????iterator.remove();
????????????????continue;
????????????}
????????????//?判斷?key?是否還有效,無(wú)效的話進(jìn)行移除
????????????if?(redisTemplate.opsForValue().get(holder.getBusinessKey())?==?null)?{
????????????????iterator.remove();
????????????????continue;
????????????}
????????????//?超時(shí)重試次數(shù),超過(guò)時(shí)給線程設(shè)定中斷
????????????if?(holder.getCurrentCount()?>?holder.getTryCount())?{
????????????????holder.getCurrentTread().interrupt();
????????????????iterator.remove();
????????????????continue;
????????????}
????????????//?判斷是否進(jìn)入最后三分之一時(shí)間
????????????long?curTime?=?System.currentTimeMillis();
????????????boolean?shouldExtend?=?(holder.getLastModifyTime()?+?holder.getModifyPeriod())?<=?curTime;
????????????if?(shouldExtend)?{
????????????????holder.setLastModifyTime(curTime);
????????????????redisTemplate.expire(holder.getBusinessKey(),?holder.getLockTime(),?TimeUnit.SECONDS);
????????????????log.info("businessKey?:?["?+?holder.getBusinessKey()?+?"],?try?count?:?"?+?holder.getCurrentCount());
????????????????holder.setCurrentCount(holder.getCurrentCount()?+?1);
????????????}
????????}
????},?0,?2,?TimeUnit.SECONDS);
}
這段代碼,用來(lái)實(shí)現(xiàn)設(shè)計(jì)圖中虛線框的思想,避免一個(gè)請(qǐng)求十分耗時(shí),導(dǎo)致提前釋放了鎖。
這里加了「線程中斷」Thread#interrupt,希望超過(guò)重試次數(shù)后,能讓線程中斷(未經(jīng)嚴(yán)謹(jǐn)測(cè)試,僅供參考哈哈哈哈)
不過(guò)建議如果遇到這么耗時(shí)的請(qǐng)求,還是能夠從根源上查找,分析耗時(shí)路徑,進(jìn)行業(yè)務(wù)優(yōu)化或其它處理,避免這些耗時(shí)操作。
所以記得多打點(diǎn) Log,分析問(wèn)題時(shí)可以更快一點(diǎn)。記錄項(xiàng)目日志,一個(gè)注解搞定
五、開(kāi)始測(cè)試
在一個(gè)入口方法中,使用該注解,然后在業(yè)務(wù)中模擬耗時(shí)請(qǐng)求,使用了 Thread#sleep
@GetMapping("/testRedisLock")
@RedisLockAnnotation(typeEnum?=?RedisLockTypeEnum.ONE,?lockTime?=?3)
public?Book?testRedisLock(@RequestParam("userId")?Long?userId)?{
????try?{
????????log.info("睡眠執(zhí)行前");
????????Thread.sleep(10000);
????????log.info("睡眠執(zhí)行后");
????}?catch?(Exception?e)?{
????????//?log?error
????????log.info("has?some?error",?e);
????}
????return?null;
}
使用時(shí),在方法上添加該注解,然后設(shè)定相應(yīng)參數(shù)即可,根據(jù) typeEnum 可以區(qū)分多種業(yè)務(wù),限制該業(yè)務(wù)被同時(shí)操作。
測(cè)試結(jié)果:
2020-04-04 14:55:50.864 INFO 9326 --- [nio-8081-exec-1] c.s.demo.controller.BookController : 睡眠執(zhí)行前
2020-04-04 14:55:52.855 INFO 9326 --- [k-schedule-pool] c.s.demo.aop.lock.RedisLockAspect : businessKey : [Business1:1024], try count : 0
2020-04-04 14:55:54.851 INFO 9326 --- [k-schedule-pool] c.s.demo.aop.lock.RedisLockAspect : businessKey : [Business1:1024], try count : 1
2020-04-04 14:55:56.851 INFO 9326 --- [k-schedule-pool] c.s.demo.aop.lock.RedisLockAspect : businessKey : [Business1:1024], try count : 2
2020-04-04 14:55:58.852 INFO 9326 --- [k-schedule-pool] c.s.demo.aop.lock.RedisLockAspect : businessKey : [Business1:1024], try count : 3
2020-04-04 14:56:00.857 INFO 9326 --- [nio-8081-exec-1] c.s.demo.controller.BookController : has some error
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method) [na:1.8.0_221]
我這里測(cè)試的是重試次數(shù)過(guò)多,失敗的場(chǎng)景,如果減少睡眠時(shí)間,就能讓業(yè)務(wù)正常執(zhí)行。
如果同時(shí)請(qǐng)求,你將會(huì)發(fā)現(xiàn)以下錯(cuò)誤信息:

表示我們的鎖的確生效了,避免了重復(fù)請(qǐng)求。
六、總結(jié)
對(duì)于耗時(shí)業(yè)務(wù)和核心數(shù)據(jù),不能讓重復(fù)的請(qǐng)求同時(shí)操作數(shù)據(jù),避免數(shù)據(jù)的不正確,所以要使用分布式鎖來(lái)對(duì)它們進(jìn)行保護(hù)。
再來(lái)梳理一下設(shè)計(jì)流程:
- 新建注解 @interface,在注解里設(shè)定入?yún)?biāo)志
- 增加 AOP 切點(diǎn),掃描特定注解
- 建立 @Aspect 切面任務(wù),注冊(cè) bean 和攔截特定方法
- 特定方法參數(shù) ProceedingJoinPoint,對(duì)方法 pjp.proceed() 前后進(jìn)行攔截
- 切點(diǎn)前進(jìn)行加鎖,任務(wù)執(zhí)行后進(jìn)行刪除 key
本次學(xué)習(xí)是通過(guò) Review 小伙伴的代碼設(shè)計(jì),從中了解分布式鎖的具體實(shí)現(xiàn),仿照他的設(shè)計(jì),重新寫(xiě)了一份簡(jiǎn)化版的業(yè)務(wù)處理。對(duì)于之前沒(méi)考慮到的「續(xù)時(shí)」操作,這里使用了守護(hù)線程來(lái)定時(shí)判斷和延長(zhǎng)超時(shí)時(shí)間,避免了鎖提前釋放。
于是乎,同時(shí)回顧了三個(gè)知識(shí)點(diǎn):
1、AOP 的實(shí)現(xiàn)和常用方法
2、定時(shí)線程池 ScheduledExecutorService 的使用和參數(shù)含義
3、線程 Thread#interrupt 的含義以及用法(這個(gè)挺有意思的,可以深入再學(xué)習(xí)一下)
以上就是SpringBoot利用注解來(lái)實(shí)現(xiàn)Redis分布式鎖的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot Redis分布式鎖的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- SpringBoot+Redis執(zhí)行l(wèi)ua腳本的5種方式總結(jié)
- Springboot+Redis執(zhí)行l(wèi)ua腳本的項(xiàng)目實(shí)踐
- springboot使用redisTemplate操作lua腳本
- springboot中使用redis并且執(zhí)行調(diào)試lua腳本
- SpringBoot通過(guò)redisTemplate調(diào)用lua腳本并打印調(diào)試信息到redis log(方法步驟詳解)
- SpringBoot通過(guò)RedisTemplate執(zhí)行Lua腳本的方法步驟
- SpringBoot+Redis執(zhí)行l(wèi)ua腳本的方法步驟
- SpringBoot基于Redis的分布式鎖實(shí)現(xiàn)過(guò)程記錄
- 關(guān)于SpringBoot 使用 Redis 分布式鎖解決并發(fā)問(wèn)題
- springboot+redis+lua實(shí)現(xiàn)分布式鎖的腳本
相關(guān)文章
Java并發(fā)中的Fork/Join 框架機(jī)制詳解
本文主要介紹了 Java 并發(fā)框架中的 Fork/Join 框架的基本原理和其使用的工作竊取算法(work-stealing)、設(shè)計(jì)方式和部分實(shí)現(xiàn)源碼,感興趣的朋友跟隨小編一起看看吧2021-07-07
詳解Java 序列化與反序列化(Serialization)
這篇文章主要介紹了Java 序列化與反序列化(Serialization),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí) 吧2019-03-03
Java springboot Mongodb增刪改查代碼實(shí)例
這篇文章主要介紹了Java springboot Mongodb增刪改查代碼實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-07-07
Java實(shí)現(xiàn)動(dòng)態(tài)獲取文件的絕對(duì)路徑
我們知道在?Java?中讀取一些配置文件信息,是在開(kāi)發(fā)中十分常用的要求。這篇文章就來(lái)和大家聊聊Java如何實(shí)現(xiàn)動(dòng)態(tài)獲取文件的絕對(duì)路徑,感興趣的可以了解一下2023-02-02
springboot實(shí)現(xiàn)防重復(fù)提交和防重復(fù)點(diǎn)擊的示例
這篇文章主要介紹了springboot實(shí)現(xiàn)防重復(fù)提交和防重復(fù)點(diǎn)擊的示例,幫助大家更好的理解和學(xué)習(xí)springboot框架,感興趣的朋友可以了解下2020-09-09
openFeign服務(wù)之間調(diào)用保持請(qǐng)求頭信息處理方式
這篇文章主要介紹了openFeign服務(wù)之間調(diào)用保持請(qǐng)求頭信息處理方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06
springboot啟動(dòng)的注意事項(xiàng)之不同包下有同樣名字的class類問(wèn)題
這篇文章主要介紹了springboot啟動(dòng)的注意事項(xiàng)之不同包下有同樣名字的class類問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06

