springboot 防止重復請求防止重復點擊的操作
利用 springboot + redis 實現(xiàn)過濾重復提交的請求,業(yè)務流程如下所示,首先定義一個攔截器,攔截需要進行過濾的URL,然后用 session + URL 作為唯一 key,利用 redis setnx 命令,來判斷請求是否重復,如果 key set 成功,說明非重復請求,失敗則說明重復請求;

URL 攔截器可以使用 spring 攔截器,但使用 spring,每個需要過濾的新 URL 都需要添加配置,因此這里使用 AOP 注解 的形式來實現(xiàn),這樣更直觀一點;
首先,定義注解:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface AvoidRepeatRequest {
/** 請求間隔時間,單位秒,該時間范圍內(nèi)的請求為重復請求 */
int intervalTime() default 5;
/** 返回的提示信息 */
String msg() default "請不要頻繁重復請求!";
}然后定義 AOP,實現(xiàn)重復請求過濾功能:
@Component
@Aspect
@Order(100)
public class FilterRepeatRequest {
private static final String SUFFIX = "REQUEST_";
@Autowired
private RedisTemplate redisTemplate;
// 定義 注解 類型的切點
@Pointcut("@annotation(com.common.ann.AvoidRepeatRequest)")
public void arrPointcut() {}
// 實現(xiàn)過濾重復請求功能
@Around("arrPointcut()")
public Object arrBusiness(ProceedingJoinPoint joinPoint) {
// 獲取 redis key,由 session ID 和 請求URI 構(gòu)成
ServletRequestAttributes sra = (ServletRequestAttributes)
RequestContextHolder.currentRequestAttributes();
HttpServletRequest request = sra.getRequest();
String key = SUFFIX + request.getSession().getId() + "_" + request.getRequestURI();
// 獲取方法的 AvoidRepeatRequest 注解
Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
AvoidRepeatRequest arr = method.getAnnotation(AvoidRepeatRequest.class);
// 判斷是否是重復的請求
if (!redisTemplate.opsForValue().setIfAbsent(key, 1, arr.intervalTime(), TimeUnit.SECONDS)) {
// 已發(fā)起過請求
System.out.println("重復請求");
return arr.msg();
}
try {
// 非重復請求,執(zhí)行業(yè)務代碼
return joinPoint.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
return "error";
}
}
}
測試使用:
@RestController
public class TestAop {
// 使用 AvoidRepeatRequest 注解的請求,表明需要進行重復請求判斷
@AvoidRepeatRequest(intervalTime = 6, msg = "慢點,兄弟")
@GetMapping("test/aop")
public String test() {
return "test aop";
}
}到此這篇關(guān)于springboot 防止重復請求防止重復點擊的操作的文章就介紹到這了,更多相關(guān)springboot 重復請求內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java開發(fā)者結(jié)合Node.js編程入門教程
這篇文章主要介紹了Java開發(fā)者結(jié)合Node.js編程入門教程,我將先向您展示如何使用Java EE創(chuàng)建一個簡單的Rest服務來讀取 MongoDB數(shù)據(jù)庫。然后我會用node.js來實現(xiàn)相同的功能,需要的朋友可以參考下2014-09-09
springboot mybatis調(diào)用多個數(shù)據(jù)源引發(fā)的錯誤問題
這篇文章主要介紹了springboot mybatis調(diào)用多個數(shù)據(jù)源引發(fā)的錯誤問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-01-01
解決mybatis-plus-boot-starter與mybatis-spring-boot-starter的錯誤問題
本文主要講述了在使用MyBatis和MyBatis-Plus時遇到的綁定異常問題,通過排查和總結(jié),作者發(fā)現(xiàn)使用MyBatis-Plus?Boot?Starter可以解決這個問題,文章詳細對比了MyBatis-Plus?Boot?Starter和MyBatis?Spring?Boot?Starter的功能和使用場景2025-01-01

