作者:jingQ
來源:https://www.sevenyuan.cn/
一、業務背景
有些業務請求,屬于耗時操作,需要加鎖,防止后續的并發操作,同時對資料庫的資料進行操作,需要避免對之前的業務造成影響,
二、分析流程
使用 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
*/
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);
}
三、設計方案
經過上面的分析,同事小??設計出了這個方案:

前面已經說了整體流程,這里強調一下幾個核心步驟:
- 攔截注解 @RedisLock,獲取必要的引數
- 加鎖操作
- 續時操作
- 結束業務,釋放鎖
四、實操
之前也有整理過 AOP 使用方法,可以參考一下
相關屬性類配置
業務屬性列舉設定
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);
}
}
任務佇列保存引數
public class RedisLockDefinitionHolder {
/**
* 業務唯一 key
*/
private String businessKey;
/**
* 加鎖時間 (秒 s)
*/
private Long lockTime;
/**
* 上次更新時間(ms)
*/
private Long lastModifyTime;
/**
* 保存當前執行緒
*/
private Thread currentTread;
/**
* 總共嘗試次數
*/
private int tryCount;
/**
* 當前嘗試次數
*/
private int currentCount;
/**
* 更新的時間周期(毫秒),公式 = 加鎖時間(轉成毫秒) / 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;
}
}
設定被攔截的注解名字
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface RedisLockAnnotation {
/**
* 特定引數識別,默認取第 0 個下標
*/
int lockFiled() default 0;
/**
* 超時重試次數
*/
int tryCount() default 3;
/**
* 自定義加鎖型別
*/
RedisLockTypeEnum typeEnum();
/**
* 釋放時間,秒 s 單位
*/
long lockTime() default 30;
}
核心切面攔截的操作
RedisLockAspect.java 該類分成三部分來描述具體作用
Pointcut 設定
/**
* @annotation 中的路徑表示攔截特定注解
*/
@Pointcut("@annotation(cn.sevenyuan.demo.aop.lock.RedisLockAnnotation)")
public void redisLockPC() {
}
Around 前后進行加鎖和釋放鎖
前面步驟定義了我們想要攔截的切點,下一步就是在切點前后做一些自定義操作:
@Around(value = "https://www.cnblogs.com/javastack/p/redisLockPC()")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
// 決議引數
Method method = resolveMethod(pjp);
RedisLockAnnotation annotation = method.getAnnotation(RedisLockAnnotation.class);
RedisLockTypeEnum typeEnum = annotation.typeEnum();
Object[] params = pjp.getArgs();
String ukString = params[annotation.lockFiled()].toString();
// 省略很多引數校驗和判空
String businessKey = typeEnum.getUniqueKey(ukString);
String uniqueValue = https://www.cnblogs.com/javastack/p/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 資訊加入「延時」佇列中
holderList.add(new RedisLockDefinitionHolder(businessKey, annotation.lockTime(), System.currentTimeMillis(),
currentThread, annotation.tryCount()));
// 執行業務操作
result = pjp.proceed();
// 執行緒被中斷,拋出例外,中斷此次請求
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 {
// 請求結束后,強制刪掉 key,釋放鎖
redisTemplate.delete(businessKey);
log.info("release the lock, businessKey is [" + businessKey + "]");
}
return result;
}
上述流程簡單總結一下:
- 決議注解引數,獲取注解值和方法上的引數值
- redis 加鎖并且設定超時時間
- 將本次 Task 資訊加入「延時」佇列中,進行續時,方式提前釋放鎖
- 加了一個執行緒中斷標志
- 結束請求,finally 中釋放鎖
續時操作
這里用了 ScheduledExecutorService,維護了一個執行緒,不斷對任務佇列中的任務進行判斷和延長超時時間:
// 掃描的任務佇列
private static ConcurrentLinkedQueue<RedisLockDefinitionHolder> holderList = new ConcurrentLinkedQueue();
/**
* 執行緒池,維護keyAliveTime
*/
private static final ScheduledExecutorService SCHEDULER = new ScheduledThreadPoolExecutor(1,
new BasicThreadFactory.Builder().namingPattern("redisLock-schedule-pool").daemon(true).build());
{
// 兩秒執行一次「續時」操作
SCHEDULER.scheduleAtFixedRate(() -> {
// 這里記得加 try-catch,否者報錯后定時任務將不會再執行=-=
Iterator<RedisLockDefinitionHolder> iterator = holderList.iterator();
while (iterator.hasNext()) {
RedisLockDefinitionHolder holder = 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;
}
// 判斷是否進入最后三分之一時間
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);
}
這段代碼,用來實作設計圖中虛線框的思想,避免一個請求十分耗時,導致提前釋放了鎖,
這里加了「執行緒中斷」Thread#interrupt,希望超過重試次數后,能讓執行緒中斷(未經嚴謹測驗,僅供參考哈哈哈哈)
不過建議如果遇到這么耗時的請求,還是能夠從根源上查找,分析耗時路徑,進行業務優化或其它處理,避免這些耗時操作,
所以記得多打點 Log,分析問題時可以更快一點,如何使用SpringBoot AOP 記錄操作日志、例外日志?
Spring Boot 基礎就不介紹了,推薦下這個實戰教程:
https://github.com/javastacks/spring-boot-best-practice
五、開始測驗
在一個入口方法中,使用該注解,然后在業務中模擬耗時請求,使用了 Thread#sleep
@GetMapping("/testRedisLock")
@RedisLockAnnotation(typeEnum = RedisLockTypeEnum.ONE, lockTime = 3)
public Book testRedisLock(@RequestParam("userId") Long userId) {
try {
log.info("睡眠執行前");
Thread.sleep(10000);
log.info("睡眠執行后");
} catch (Exception e) {
// log error
log.info("has some error", e);
}
return null;
}
使用時,在方法上添加該注解,然后設定相應引數即可,根據 typeEnum 可以區分多種業務,限制該業務被同時操作,
測驗結果:
2020-04-04 14:55:50.864 INFO 9326 --- [nio-8081-exec-1] c.s.demo.controller.BookController : 睡眠執行前
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]
我這里測驗的是重試次數過多,失敗的場景,如果減少睡眠時間,就能讓業務正常執行,
如果同時請求,你將會發現以下錯誤資訊:

表示我們的鎖??的確生效了,避免了重復請求,
六、總結
對于耗時業務和核心資料,不能讓重復的請求同時操作資料,避免資料的不正確,所以要使用分布式鎖來對它們進行保護,
再來梳理一下設計流程:
- 新建注解 @interface,在注解里設定入參標志
- 增加 AOP 切點,掃描特定注解
- 建立 @Aspect 切面任務,注冊 bean 和攔截特定方法
- 特定方法引數 ProceedingJoinPoint,對方法 pjp.proceed() 前后進行攔截
- 切點前進行加鎖,任務執行后進行洗掉 key
本次學習是通過 Review 小伙伴的代碼設計,從中了解分布式鎖的具體實作,仿照他的設計,重新寫了一份簡化版的業務處理,對于之前沒考慮到的「續時」操作,這里使用了守護執行緒來定時判斷和延長超時時間,避免了鎖提前釋放,
于是乎,同時回顧了三個知識點:
1、AOP 的實作和常用方法
2、定時執行緒池 ScheduledExecutorService 的使用和引數含義
3、執行緒 Thread#interrupt 的含義以及用法(這個挺有意思的,可以深入再學習一下)
參考資料:
- https://blog.csdn.net/XWForever/article/details/103163021
- https://www.zhihu.com/question/41048032
近期熱文推薦:
1.1,000+ 道 Java面試題及答案整理(2022最新版)
2.勁爆!Java 協程要來了,,,
3.Spring Boot 2.x 教程,太全了!
4.別再寫滿屏的爆爆爆炸類了,試試裝飾器模式,這才是優雅的方式!!
5.《Java開發手冊(嵩山版)》最新發布,速速下載!
覺得不錯,別忘了隨手點贊+轉發哦!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/503332.html
標籤:Java
上一篇:微服務網關Gateway實踐總結
下一篇:基礎資料型別之集合
