一個(gè)注解,兩種實(shí)現(xiàn)方式完美解決重復(fù)提交問題
環(huán)境:Springboot3.0.5
什么是接口防重
接口防重是指在一定時(shí)間內(nèi)只允許執(zhí)行一次接口請(qǐng)求。這是為了防止由于重復(fù)提交和重復(fù)處理產(chǎn)生重復(fù)數(shù)據(jù)或相應(yīng)錯(cuò)誤。實(shí)現(xiàn)接口防重可以采用以下方法:
- 使用唯一標(biāo)識(shí)符:在請(qǐng)求中包含一個(gè)唯一標(biāo)識(shí)符(例如請(qǐng)求token),然后在對(duì)應(yīng)接口判斷該唯一值在一定時(shí)間內(nèi)是否被消費(fèi)過,如果已被消費(fèi),則拒絕該請(qǐng)求。
- 使用時(shí)間戳、計(jì)數(shù)器等機(jī)制:記錄請(qǐng)求的時(shí)間或次數(shù),并在一定范圍內(nèi)拒絕重復(fù)請(qǐng)求。
- 采用Spring AOP理念:實(shí)現(xiàn)請(qǐng)求的切割,在請(qǐng)求執(zhí)行到某個(gè)方法或某層時(shí),開始攔截并進(jìn)行防重處理。
這些方法有助于確保系統(tǒng)的一致性和穩(wěn)定性,防止數(shù)據(jù)的重復(fù)提交和處理。
冪等與防重
API接口的冪等性和防重性是兩個(gè)不同的概念,盡管它們?cè)谀承┓矫嬗兄丿B之處。
- 冪等性
冪等性是指一個(gè)操作或API請(qǐng)求,無論執(zhí)行一次還是多次,結(jié)果都是相同的。在API設(shè)計(jì)中,冪等性是一種非常重要的屬性,因?yàn)樗_保了在重試或并發(fā)請(qǐng)求時(shí),系統(tǒng)狀態(tài)不會(huì)出現(xiàn)不一致的情況。
在實(shí)現(xiàn)冪等性時(shí),通常采用以下方法:
- 在請(qǐng)求中包含一個(gè)唯一標(biāo)識(shí)符(例如請(qǐng)求ID),以便在處理請(qǐng)求時(shí)能夠識(shí)別和防止重復(fù)處理。
- 使用樂觀鎖或悲觀鎖機(jī)制來保證數(shù)據(jù)的一致性。
- 對(duì)于更新操作,可以通過比較新舊數(shù)據(jù)來判斷是否有變化,只有當(dāng)數(shù)據(jù)發(fā)生改變時(shí)才執(zhí)行更新操作。
- 防重性
防重性是指在一定時(shí)間內(nèi)只允許執(zhí)行一次操作或請(qǐng)求。它主要用于防止重復(fù)提交和重復(fù)處理。與冪等性不同,防重性主要關(guān)注的是防止數(shù)據(jù)重復(fù),而冪等性則關(guān)注任何多次執(zhí)行的結(jié)果都是相同的。
技術(shù)實(shí)現(xiàn)
方式1:通過AOP方式
自定義注解
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface PreventDuplicate {
/**
* 唯一標(biāo)識(shí)通過header傳遞時(shí)的key
*
* @return
*/
String header() default "token" ;
/**
* 唯一標(biāo)識(shí)通過請(qǐng)求參數(shù)傳遞時(shí)的key
*
* @return
*/
String param() default "token" ;
}
自定義AOP切面
@Component
@Aspect
public class PreventDuplicateAspect {
public static final String PREVENT_PREFIX_KEY = "prevent:" ;
private final StringRedisTemplate stringRedisTemplate ;
private final HttpServletRequest request ;
public PreventDuplicateAspect(StringRedisTemplate stringRedisTemplate, HttpServletRequest request) {
this.stringRedisTemplate = stringRedisTemplate ;
this.request = request ;
}
@Around("@annotation(prevent)")
public Object preventDuplicate(ProceedingJoinPoint pjp, PreventDuplicate prevent) throws Throwable {
String key = prevent.header() ;
String value = null ;
if (key != null && key.length() > 0) {
value = this.request.getHeader(key) ;
} else {
key = prevent.param() ;
if (key != null && key.length() > 0) {
value = this.request.getParameter(key) ;
}
}
if (value == null || "".equals(value.trim())) {
return "非法請(qǐng)求" ;
}
// 拼接rediskey
String prevent_key = PREVENT_PREFIX_KEY + value ;
// 判斷redis中是否存在當(dāng)前請(qǐng)求中攜帶的唯一標(biāo)識(shí)數(shù)據(jù), 刪除成功則存在
Boolean result = this.stringRedisTemplate.delete(prevent_key) ;
if (result != null && result.booleanValue()) {
return pjp.proceed() ;
} else {
return "請(qǐng)不要重復(fù)提交" ;
}
}
}
生成唯一標(biāo)識(shí)接口
@RestController
@RequestMapping("/generate")
public class GenerateController {
private final StringRedisTemplate stringRedisTemplate ;
public GenerateController(StringRedisTemplate stringRedisTemplate) {
this.stringRedisTemplate = stringRedisTemplate ;
}
@GetMapping("/token")
public String token() {
String token = UUID.randomUUID().toString().replace("-", "") ;
// 將生成的token存入redis中,設(shè)置有效期5分鐘
this.stringRedisTemplate.opsForValue().setIfAbsent(PreventDuplicateAspect.PREVENT_PREFIX_KEY + token, token, 5 * 60, TimeUnit.SECONDS) ;
return token ;
}
}
業(yè)務(wù)接口
@RestController
@RequestMapping("/prevent")
public class PreventController {
@PreventDuplicate
@GetMapping("/index")
public Object index() {
return "index success" ;
}
}
測試
先調(diào)用生成唯一接口獲取token值
圖片
調(diào)用業(yè)務(wù)接口,攜帶token值
第一次訪問, 正常
再次訪問
方式2:通過攔截器實(shí)現(xiàn)
自定義攔截器
@Component
public class PreventDuplicateInterceptor implements HandlerInterceptor {
private final StringRedisTemplate stringRedisTemplate ;
public PreventDuplicateInterceptor(StringRedisTemplate stringRedisTemplate) {
this.stringRedisTemplate = stringRedisTemplate ;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (handler instanceof HandlerMethod hm) {
if (hm.hasMethodAnnotation(PreventDuplicate.class)) {
PreventDuplicate pd = hm.getMethodAnnotation(PreventDuplicate.class) ;
String key = pd.header() ;
String value = null ;
if (key != null && key.length() > 0) {
value = request.getHeader(key) ;
} else {
key = pd.param() ;
if (key != null && key.length() > 0) {
value = request.getParameter(key) ;
}
}
if (value == null || "".equals(value.trim())) {
response.setContentType("text/plain;charset=utf-8") ;
response.getWriter().println("非法請(qǐng)求") ;
return false ;
}
// 拼接rediskey
String prevent_key = PreventDuplicateAspect.PREVENT_PREFIX_KEY + value ;
// 判斷redis中是否存在當(dāng)前請(qǐng)求中攜帶的唯一標(biāo)識(shí)數(shù)據(jù), 刪除成功則存在
Boolean result = this.stringRedisTemplate.delete(prevent_key) ;
if (result != null && result.booleanValue()) {
return true ;
} else {
response.setContentType("text/plain;charset=utf-8") ;
response.getWriter().println("請(qǐng)不要重復(fù)提交") ;
return false ;
}
}
}
return true ;
}
}
配置攔截器
@Component
public class PreventWebConfig implements WebMvcConfigurer {
private final PreventDuplicateInterceptor duplicateInterceptor ;
public PreventWebConfig(PreventDuplicateInterceptor duplicateInterceptor) {
this.duplicateInterceptor = duplicateInterceptor ;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(this.duplicateInterceptor).addPathPatterns("/**") ;
}
}
測試
獲取token
第一次請(qǐng)求
再次請(qǐng)求
完畢!?。?/p>