點擊關注公眾號,實用技術文章及時了解
有些業務請求,屬於耗時操作,需要加鎖,防止後續的並發操作,同時對數據庫的數據進行操作,需要避免對之前的業務造成影響。
2. 分析流程使用Redis作為分布式鎖,將鎖的狀態放到Redis統一維護,解決集群中單機JVM信息不互通的問題,規定操作順序,保護用戶的數據正確。
梳理設計流程
新建註解 @interface,在註解里設定入參標誌
增加 AOP 切點,掃描特定註解
建立 @Aspect 切面任務,註冊 bean 和攔截特定方法
特定方法參數 ProceedingJoinPoint,對方法 pjp.proceed() 前後進行攔截
切點前進行加鎖,任務執行後進行刪除 key
核心步驟:加鎖、解鎖和續時
加鎖使用了 RedisTemplate 的 opsForValue.setIfAbsent 方法,判斷是否有 key,設定一個隨機數 UUID.random().toString,生成一個隨機數作為 value。
從 redis 中獲取鎖之後,對 key 設定 expire 失效時間,到期後自動釋放鎖。
按照這種設計,只有第一個成功設定Key的請求,才能進行後續的數據操作,後續其它請求由於無法獲得🔐資源,將會失敗結束。
超時問題擔心pjp.proceed()切點執行的方法太耗時,導致Redis中的key由於超時提前釋放了。
例如,線程 A 先獲取鎖,proceed 方法耗時,超過了鎖超時時間,到期釋放了鎖,這時另一個線程 B 成功獲取Redis鎖,兩個線程同時對同一批數據進行操作,導致數據不準確。
解決方案:增加一個「續時」任務不完成,鎖不釋放:
維護了一個定時線程池ScheduledExecutorService,每隔 2s 去掃描加入隊列中的 Task,判斷是否失效時間是否快到了,公式為:【失效時間】<= 【當前時間】+【失效間隔(三分之一超時)】
/***線程池,每個JVM使用一個線程去維護keyAliveTime,定時執行runnable*/privatestaticfinalScheduledExecutorServiceSCHEDULER=newScheduledThreadPoolExecutor(1,newBasicThreadFactory.Builder().namingPattern("redisLock-schedule-pool").daemon(true).build());static{SCHEDULER.scheduleAtFixedRate(()->{//dosomethingtoextendtime},0,2,TimeUnit.SECONDS);}3. 設計方案經過上面的分析,設計出了這個方案:

前面已經說了整體流程,這裡強調一下幾個核心步驟:
攔截註解 @RedisLock,獲取必要的參數
加鎖操作
續時操作
結束業務,釋放鎖
之前也有整理過AOP使用方法,可以參考一下
相關屬性類配置業務屬性枚舉設定publicenumRedisLockTypeEnum{/***自定義key前綴*/ONE("Business1","Test1"),TWO("Business2","Test2");privateStringcode;privateStringdesc;RedisLockTypeEnum(Stringcode,Stringdesc){this.code=code;this.desc=desc;}publicStringgetCode(){returncode;}publicStringgetDesc(){returndesc;}publicStringgetUniqueKey(Stringkey){returnString.format("%s:%s",this.getCode(),key);}}任務隊列保存參數publicclassRedisLockDefinitionHolder{/***業務唯一key*/privateStringbusinessKey;/***加鎖時間(秒s)*/privateLonglockTime;/***上次更新時間(ms)*/privateLonglastModifyTime;/***保存當前線程*/privateThreadcurrentTread;/***總共嘗試次數*/privateinttryCount;/***當前嘗試次數*/privateintcurrentCount;/***更新的時間周期(毫秒),公式=加鎖時間(轉成毫秒)/3*/privateLongmodifyPeriod;publicRedisLockDefinitionHolder(StringbusinessKey,LonglockTime,LonglastModifyTime,ThreadcurrentTread,inttryCount){this.businessKey=businessKey;this.lockTime=lockTime;this.lastModifyTime=lastModifyTime;this.currentTread=currentTread;this.tryCount=tryCount;this.modifyPeriod=lockTime*1000/3;}}設定被攔截的註解名字@Retention(RetentionPolicy.RUNTIME)@Target({ElementType.METHOD,ElementType.TYPE})public@interfaceRedisLockAnnotation{/***特定參數識別,默認取第0個下標*/intlockFiled()default0;/***超時重試次數*/inttryCount()default3;/***自定義加鎖類型*/RedisLockTypeEnumtypeEnum();/***釋放時間,秒s單位*/longlockTime()default30;}核心切面攔截的操作RedisLockAspect.java該類分成三部分來描述具體作用
Pointcut 設定/***@annotation中的路徑表示攔截特定註解*/@Pointcut("@annotation(cn.sevenyuan.demo.aop.lock.RedisLockAnnotation)")publicvoidredisLockPC(){}Around 前後進行加鎖和釋放鎖前面步驟定義了我們想要攔截的切點,下一步就是在切點前後做一些自定義操作:
@Around(value="redisLockPC()")publicObjectaround(ProceedingJoinPointpjp)throwsThrowable{//解析參數Methodmethod=resolveMethod(pjp);RedisLockAnnotationannotation=method.getAnnotation(RedisLockAnnotation.class);RedisLockTypeEnumtypeEnum=annotation.typeEnum();Object[]params=pjp.getArgs();StringukString=params[annotation.lockFiled()].toString();//省略很多參數校驗和判空StringbusinessKey=typeEnum.getUniqueKey(ukString);StringuniqueValue=UUID.randomUUID().toString();//加鎖Objectresult=null;try{booleanisSuccess=redisTemplate.opsForValue().setIfAbsent(businessKey,uniqueValue);if(!isSuccess){thrownewException("Youcan'tdoit,becauseanotherhasgetthelock=-=");}redisTemplate.expire(businessKey,annotation.lockTime(),TimeUnit.SECONDS);ThreadcurrentThread=Thread.currentThread();//將本次Task信息加入「延時」隊列中holderList.add(newRedisLockDefinitionHolder(businessKey,annotation.lockTime(),System.currentTimeMillis(),currentThread,annotation.tryCount()));//執行業務操作result=pjp.proceed();//線程被中斷,拋出異常,中斷此次請求if(currentThread.isInterrupted()){thrownewInterruptedException("Youhadbeeninterrupted=-=");}}catch(InterruptedExceptione){log.error("Interruptexception,rollbacktransaction",e);thrownewException("Interruptexception,pleasesendrequestagain");}catch(Exceptione){log.error("hassomeerror,pleasecheckagain",e);}finally{//請求結束後,強制刪掉key,釋放鎖redisTemplate.delete(businessKey);log.info("releasethelock,businessKeyis["+businessKey+"]");}returnresult;}上述流程簡單總結一下:
解析註解參數,獲取註解值和方法上的參數值
redis 加鎖並且設置超時時間
將本次 Task 信息加入「延時」隊列中,進行續時,方式提前釋放鎖
加了一個線程中斷標誌
結束請求,finally 中釋放鎖
這裡用了ScheduledExecutorService,維護了一個線程,不斷對任務隊列中的任務進行判斷和延長超時時間:
//掃描的任務隊列privatestaticConcurrentLinkedQueue<RedisLockDefinitionHolder>holderList=newConcurrentLinkedQueue();/***線程池,維護keyAliveTime*/privatestaticfinalScheduledExecutorServiceSCHEDULER=newScheduledThreadPoolExecutor(1,newBasicThreadFactory.Builder().namingPattern("redisLock-schedule-pool").daemon(true).build());{//兩秒執行一次「續時」操作SCHEDULER.scheduleAtFixedRate(()->{//這裡記得加try-catch,否者報錯後定時任務將不會再執行=-=Iterator<RedisLockDefinitionHolder>iterator=holderList.iterator();while(iterator.hasNext()){RedisLockDefinitionHolderholder=iterator.next();//判空if(holder==null){iterator.remove();continue;}//判斷key是否還有效,無效的話進行移除if(redisTemplate.opsForValue().get(holder.getBusinessKey())==null){iterator.remove();continue;}//超時重試次數,超過時給線程設定中斷if(holder.getCurrentCount()>holder.getTryCount()){holder.getCurrentTread().interrupt();iterator.remove();continue;}//判斷是否進入最後三分之一時間longcurTime=System.currentTimeMillis();booleanshouldExtend=(holder.getLastModifyTime()+holder.getModifyPeriod())<=curTime;if(shouldExtend){holder.setLastModifyTime(curTime);redisTemplate.expire(holder.getBusinessKey(),holder.getLockTime(),TimeUnit.SECONDS);log.info("businessKey:["+holder.getBusinessKey()+"],trycount:"+holder.getCurrentCount());holder.setCurrentCount(holder.getCurrentCount()+1);}}},0,2,TimeUnit.SECONDS);}這段代碼,用來實現設計圖中虛線框的思想,避免一個請求十分耗時,導致提前釋放了鎖。
這裡加了「線程中斷」**Thread#interrupt,希望超過重試次數後,能讓線程中斷**(未經嚴謹測試,僅供參考哈哈哈哈)
不過建議如果遇到這麼耗時的請求,還是能夠從根源上查找,分析耗時路徑,進行業務優化或其它處理,避免這些耗時操作。
所以記得多打點Log,分析問題時可以更快一點。記錄項目日誌,一個註解搞定
五、開始測試在一個入口方法中,使用該註解,然後在業務中模擬耗時請求,使用了Thread#sleep
@GetMapping("/testRedisLock")@RedisLockAnnotation(typeEnum=RedisLockTypeEnum.ONE,lockTime=3)publicBooktestRedisLock(@RequestParam("userId")LonguserId){try{log.info("睡眠執行前");Thread.sleep(10000);log.info("睡眠執行後");}catch(Exceptione){//logerrorlog.info("hassomeerror",e);}returnnull;}使用時,在方法上添加該註解,然後設定相應參數即可,根據typeEnum可以區分多種業務,限制該業務被同時操作。
測試結果:
2020-04-0414:55:50.864INFO9326---[nio-8081-exec-1]c.s.demo.controller.BookController:睡眠執行前2020-04-0414:55:52.855INFO9326---[k-schedule-pool]c.s.demo.aop.lock.RedisLockAspect:businessKey:[Business1:1024],trycount:02020-04-0414:55:54.851INFO9326---[k-schedule-pool]c.s.demo.aop.lock.RedisLockAspect:businessKey:[Business1:1024],trycount:12020-04-0414:55:56.851INFO9326---[k-schedule-pool]c.s.demo.aop.lock.RedisLockAspect:businessKey:[Business1:1024],trycount:22020-04-0414:55:58.852INFO9326---[k-schedule-pool]c.s.demo.aop.lock.RedisLockAspect:businessKey:[Business1:1024],trycount:32020-04-0414:56:00.857INFO9326---[nio-8081-exec-1]c.s.demo.controller.BookController:hassomeerrorjava.lang.InterruptedException:sleepinterruptedatjava.lang.Thread.sleep(NativeMethod)[na:1.8.0_221]我這裡測試的是重試次數過多,失敗的場景,如果減少睡眠時間,就能讓業務正常執行。
如果同時請求,你將會發現以下錯誤信息:

表示我們的鎖🔐的確生效了,避免了重複請求。
六、總結對於耗時業務和核心數據,不能讓重複的請求同時操作數據,避免數據的不正確,所以要使用分布式鎖來對它們進行保護。
再來梳理一下設計流程:
新建註解 @interface,在註解里設定入參標誌
增加 AOP 切點,掃描特定註解
建立 @Aspect 切面任務,註冊 bean 和攔截特定方法
特定方法參數 ProceedingJoinPoint,對方法 pjp.proceed() 前後進行攔截
切點前進行加鎖,任務執行後進行刪除 key
本次學習是通過Review小夥伴的代碼設計,從中了解分布式鎖的具體實現,仿照他的設計,重新寫了一份簡化版的業務處理。對於之前沒考慮到的「續時」操作,這裡使用了守護線程來定時判斷和延長超時時間,避免了鎖提前釋放。
於是乎,同時回顧了三個知識點:
1、AOP的實現和常用方法
2、定時線程池ScheduledExecutorService的使用和參數含義
3、線程Thread#interrupt的含義以及用法(這個挺有意思的,可以深入再學習一下)
感謝閱讀,希望對你有所幫助:)
來源:https://www.sevenyuan.cn/
推薦
Java面試題寶典
技術內卷群,一起來學習!!
PS:因為公眾號平台更改了推送規則,如果不想錯過內容,記得讀完點一下「在看」,加個「星標」,這樣每次新文章推送才會第一時間出現在你的訂閱列表里。點「在看」支持我們吧!