Spring Boot使用AOP防止重復(fù)提交的方法示例
在傳統(tǒng)的web項(xiàng)目中,防止重復(fù)提交,通常做法是:后端生成一個(gè)唯一的提交令牌(uuid),并存儲(chǔ)在服務(wù)端。頁面提交請(qǐng)求攜帶這個(gè)提交令牌,后端驗(yàn)證并在第一次驗(yàn)證后刪除該令牌,保證提交請(qǐng)求的唯一性。
上述的思路其實(shí)沒有問題的,但是需要前后端都稍加改動(dòng),如果在業(yè)務(wù)開發(fā)完在加這個(gè)的話,改動(dòng)量未免有些大了,本節(jié)的實(shí)現(xiàn)方案無需前端配合,純后端處理。
思路
- 自定義注解 @NoRepeatSubmit 標(biāo)記所有Controller中的提交請(qǐng)求
- 通過AOP 對(duì)所有標(biāo)記了 @NoRepeatSubmit 的方法攔截
- 在業(yè)務(wù)方法執(zhí)行前,獲取當(dāng)前用戶的 token(或者JSessionId)+ 當(dāng)前請(qǐng)求地址,作為一個(gè)唯一 KEY,去獲取 Redis 分布式鎖(如果此時(shí)并發(fā)獲取,只有一個(gè)線程會(huì)成功獲取鎖)
- 業(yè)務(wù)方法執(zhí)行后,釋放鎖
關(guān)于Redis 分布式鎖
不了解的同學(xué)戳這里 ==> Redis分布式鎖的正確實(shí)現(xiàn)方式
使用Redis 是為了在負(fù)載均衡部署,如果是單機(jī)的部署的項(xiàng)目可以使用一個(gè)線程安全的本地Cache 替代 Redis
Code
這里只貼出 AOP 類和測(cè)試類,完整代碼見 ==> Gitee
@Aspect
@Component
public class RepeatSubmitAspect {
private static final Logger LOGGER = LoggerFactory.getLogger(RepeatSubmitAspect.class);
@Autowired
private RedisLock redisLock;
@Pointcut("@annotation(com.gitee.taven.aop.NoRepeatSubmit)")
public void pointCut() {}
@Around("pointCut()")
public Object before(ProceedingJoinPoint pjp) {
try {
HttpServletRequest request = RequestUtils.getRequest();
Assert.notNull(request, "request can not null");
// 此處可以用token或者JSessionId
String token = request.getHeader("Authorization");
String path = request.getServletPath();
String key = getKey(token, path);
String clientId = getClientId();
boolean isSuccess = redisLock.tryLock(key, clientId, 10);
LOGGER.info("tryLock key = [{}], clientId = [{}]", key, clientId);
if (isSuccess) {
LOGGER.info("tryLock success, key = [{}], clientId = [{}]", key, clientId);
// 獲取鎖成功, 執(zhí)行進(jìn)程
Object result = pjp.proceed();
// 解鎖
redisLock.releaseLock(key, clientId);
LOGGER.info("releaseLock success, key = [{}], clientId = [{}]", key, clientId);
return result;
} else {
// 獲取鎖失敗,認(rèn)為是重復(fù)提交的請(qǐng)求
LOGGER.info("tryLock fail, key = [{}]", key);
return new ApiResult(200, "重復(fù)請(qǐng)求,請(qǐng)稍后再試", null);
}
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return new ApiResult(500, "系統(tǒng)異常", null);
}
private String getKey(String token, String path) {
return token + path;
}
private String getClientId() {
return UUID.randomUUID().toString();
}
}
多線程測(cè)試
測(cè)試代碼如下,模擬十個(gè)請(qǐng)求并發(fā)同時(shí)提交
@Component
public class RunTest implements ApplicationRunner {
private static final Logger LOGGER = LoggerFactory.getLogger(RunTest.class);
@Autowired
private RestTemplate restTemplate;
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("執(zhí)行多線程測(cè)試");
String url="http://localhost:8000/submit";
CountDownLatch countDownLatch = new CountDownLatch(1);
ExecutorService executorService = Executors.newFixedThreadPool(10);
for(int i=0; i<10; i++){
String userId = "userId" + i;
HttpEntity request = buildRequest(userId);
executorService.submit(() -> {
try {
countDownLatch.await();
System.out.println("Thread:"+Thread.currentThread().getName()+", time:"+System.currentTimeMillis());
ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
System.out.println("Thread:"+Thread.currentThread().getName() + "," + response.getBody());
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
countDownLatch.countDown();
}
private HttpEntity buildRequest(String userId) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", "yourToken");
Map<String, Object> body = new HashMap<>();
body.put("userId", userId);
return new HttpEntity<>(body, headers);
}
}
成功防止重復(fù)提交,控制臺(tái)日志如下,可以看到十個(gè)線程的啟動(dòng)時(shí)間幾乎同時(shí)發(fā)起,只有一個(gè)請(qǐng)求提交成功了

本節(jié)demo
戳這里 ==> Gitee
build項(xiàng)目之后,啟動(dòng)本地redis,運(yùn)行項(xiàng)目自動(dòng)執(zhí)行測(cè)試方法
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java日常練習(xí)題,每天進(jìn)步一點(diǎn)點(diǎn)(60)
下面小編就為大家?guī)硪黄狫ava基礎(chǔ)的幾道練習(xí)題(分享)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧,希望可以幫到你2021-08-08
Java簡(jiǎn)單實(shí)現(xiàn)銀行ATM系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了Java簡(jiǎn)單實(shí)現(xiàn)銀行ATM系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-05-05
關(guān)于kafka-consumer-offset位移問題
這篇文章主要介紹了關(guān)于kafka-consumer-offset位移問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-03-03
Java線程安全解決方案(synchronized,ReentrantLock,Atomic)
這篇文章主要介紹了Java線程安全解決方案(synchronized,ReentrantLock,Atomic),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09
Java執(zhí)行cmd命令兩種實(shí)現(xiàn)方法解析
這篇文章主要介紹了Java執(zhí)行cmd命令兩種實(shí)現(xiàn)方法解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-07-07
基于Spring Security的Oauth2授權(quán)實(shí)現(xiàn)方法
這篇文章主要介紹了基于Spring Security的Oauth2授權(quán)實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09
通過prometheus監(jiān)控springboot程序運(yùn)行狀態(tài)的操作流程
jmx_exporter用于從Java應(yīng)用程序中提取JMX指標(biāo),適用于SpringBoot應(yīng)用,通過下載jar包和配置文件,可以抓取JVM基礎(chǔ)指標(biāo),要獲取應(yīng)用級(jí)別指標(biāo),需要集成Prometheus客戶端庫并自定義指標(biāo),本文給大家介紹了如何通過prometheus監(jiān)控springboot程序運(yùn)行狀態(tài)2025-02-02

