Spring Boot使用AOP防止重復(fù)提交的方法示例
在傳統(tǒng)的web項目中,防止重復(fù)提交,通常做法是:后端生成一個唯一的提交令牌(uuid),并存儲在服務(wù)端。頁面提交請求攜帶這個提交令牌,后端驗證并在第一次驗證后刪除該令牌,保證提交請求的唯一性。
上述的思路其實沒有問題的,但是需要前后端都稍加改動,如果在業(yè)務(wù)開發(fā)完在加這個的話,改動量未免有些大了,本節(jié)的實現(xiàn)方案無需前端配合,純后端處理。
思路
- 自定義注解 @NoRepeatSubmit 標(biāo)記所有Controller中的提交請求
- 通過AOP 對所有標(biāo)記了 @NoRepeatSubmit 的方法攔截
- 在業(yè)務(wù)方法執(zhí)行前,獲取當(dāng)前用戶的 token(或者JSessionId)+ 當(dāng)前請求地址,作為一個唯一 KEY,去獲取 Redis 分布式鎖(如果此時并發(fā)獲取,只有一個線程會成功獲取鎖)
- 業(yè)務(wù)方法執(zhí)行后,釋放鎖
關(guān)于Redis 分布式鎖
不了解的同學(xué)戳這里 ==> Redis分布式鎖的正確實現(xiàn)方式
使用Redis 是為了在負載均衡部署,如果是單機的部署的項目可以使用一個線程安全的本地Cache 替代 Redis
Code
這里只貼出 AOP 類和測試類,完整代碼見 ==> 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í)行進程
Object result = pjp.proceed();
// 解鎖
redisLock.releaseLock(key, clientId);
LOGGER.info("releaseLock success, key = [{}], clientId = [{}]", key, clientId);
return result;
} else {
// 獲取鎖失敗,認為是重復(fù)提交的請求
LOGGER.info("tryLock fail, key = [{}]", key);
return new ApiResult(200, "重復(fù)請求,請稍后再試", 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();
}
}
多線程測試
測試代碼如下,模擬十個請求并發(fā)同時提交
@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í)行多線程測試");
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ù)提交,控制臺日志如下,可以看到十個線程的啟動時間幾乎同時發(fā)起,只有一個請求提交成功了

本節(jié)demo
戳這里 ==> Gitee
build項目之后,啟動本地redis,運行項目自動執(zhí)行測試方法
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
解決 IDEA 創(chuàng)建 Gradle 項目沒有src目錄問題
這篇文章主要介紹了解決 IDEA 創(chuàng)建 Gradle 項目沒有src目錄問題,本文圖文并茂給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2018-06-06
Spring+SpringMVC+JDBC實現(xiàn)登錄的示例(附源碼)
這篇文章主要介紹了Spring+SpringMVC+JDBC實現(xiàn)登錄的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-05-05
java讀取文件:char的ASCII碼值=65279,顯示是一個空字符的解決
這篇文章主要介紹了java讀取文件:char的ASCII碼值=65279,顯示是一個空字符的解決,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08
Java編程思想中關(guān)于并發(fā)的總結(jié)
在本文中小編給大家整理的是關(guān)于Java編程思想中關(guān)于并發(fā)的總結(jié)以及相關(guān)實例內(nèi)容,需要的朋友們參考下。2019-09-09
Java中BeanUtils.copyProperties基本用法與小坑
本文主要介紹了Java中BeanUtils.copyProperties基本用法與小坑,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-04-04
MyBatis 動態(tài)SQL之where標(biāo)簽的使用
本文主要介紹了MyBatis 動態(tài)SQL之where標(biāo)簽,where 標(biāo)簽主要用來簡化 SQL 語句中的條件判斷,可以自動處理 AND/OR 條件,下面就來具體介紹一下2024-01-01

