詳解Springboot如何通過(guò)注解實(shí)現(xiàn)接口防刷
前言
本文介紹一種極簡(jiǎn)潔、靈活通用接口防刷實(shí)現(xiàn)方式、通過(guò)在需要防刷的方法加上@Prevent 注解即可實(shí)現(xiàn)短信防刷;
使用方式大致如下:
/**
* 測(cè)試防刷
*
* @param request
* @return
*/
@ResponseBody
@GetMapping(value = "/testPrevent")
@Prevent //加上該注解即可實(shí)現(xiàn)短信防刷(默認(rèn)一分鐘內(nèi)不允許重復(fù)調(diào)用,支持?jǐn)U展、配置)
public Response testPrevent(TestRequest request) {
return Response.success("調(diào)用成功");
}
1、實(shí)現(xiàn)防刷切面PreventAop.java
大致邏輯為:定義一切面,通過(guò)@Prevent注解作為切入點(diǎn)、在該切面的前置通知獲取該方法的所有入?yún)⒉⑵銪ase64編碼,將入?yún)ase64編碼+完整方法名作為redis的key,入?yún)⒆鳛閞eids的value,@Prevent的value作為redis的expire,存入redis;每次進(jìn)來(lái)這個(gè)切面根據(jù)入?yún)ase64編碼+完整方法名判斷redis值是否存在,存在則攔截防刷,不存在則允許調(diào)用;
1.1 定義注解Prevent
package com.zetting.aop;
import java.lang.annotation.*;
/**
* 接口防刷注解
* 使用:
* 在相應(yīng)需要防刷的方法上加上
* 該注解,即可
*
* @author: zetting
* @date:2018/12/29
*/
@Documented
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Prevent {
/**
* 限制的時(shí)間值(秒)
*
* @return
*/
String value() default "60";
/**
* 提示
*/
String message() default "";
/**
* 策略
*
* @return
*/
PreventStrategy strategy() default PreventStrategy.DEFAULT;
}
1.2 實(shí)現(xiàn)防刷切面PreventAop
package com.zetting.aop;
import com.alibaba.fastjson.JSON;
import com.zetting.common.BusinessException;
import com.zetting.util.RedisUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.lang.reflect.Method;
import java.util.Base64;
/**
* 防刷切面實(shí)現(xiàn)類
*
* @author: zetting
* @date: 2018/12/29 20:27
*/
@Aspect
@Component
public class PreventAop {
private static Logger log = LoggerFactory.getLogger(PreventAop.class);
@Autowired
private RedisUtil redisUtil;
/**
* 切入點(diǎn)
*/
@Pointcut("@annotation(com.zetting.aop.Prevent)")
public void pointcut() {
}
/**
* 處理前
*
* @return
*/
@Before("pointcut()")
public void joinPoint(JoinPoint joinPoint) throws Exception {
String requestStr = JSON.toJSONString(joinPoint.getArgs()[0]);
if (StringUtils.isEmpty(requestStr) || requestStr.equalsIgnoreCase("{}")) {
throw new BusinessException("[防刷]入?yún)⒉辉试S為空");
}
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
Method method = joinPoint.getTarget().getClass().getMethod(methodSignature.getName(),
methodSignature.getParameterTypes());
Prevent preventAnnotation = method.getAnnotation(Prevent.class);
String methodFullName = method.getDeclaringClass().getName() + method.getName();
entrance(preventAnnotation, requestStr,methodFullName);
return;
}
/**
* 入口
*
* @param prevent
* @param requestStr
*/
private void entrance(Prevent prevent, String requestStr,String methodFullName) throws Exception {
PreventStrategy strategy = prevent.strategy();
switch (strategy) {
case DEFAULT:
defaultHandle(requestStr, prevent,methodFullName);
break;
default:
throw new BusinessException("無(wú)效的策略");
}
}
/**
* 默認(rèn)處理方式
*
* @param requestStr
* @param prevent
*/
private void defaultHandle(String requestStr, Prevent prevent,String methodFullName) throws Exception {
String base64Str = toBase64String(requestStr);
long expire = Long.parseLong(prevent.value());
String resp = redisUtil.get(methodFullName+base64Str);
if (StringUtils.isEmpty(resp)) {
redisUtil.set(methodFullName+base64Str, requestStr, expire);
} else {
String message = !StringUtils.isEmpty(prevent.message()) ? prevent.message() :
expire + "秒內(nèi)不允許重復(fù)請(qǐng)求";
throw new BusinessException(message);
}
}
/**
* 對(duì)象轉(zhuǎn)換為base64字符串
*
* @param obj 對(duì)象值
* @return base64字符串
*/
private String toBase64String(String obj) throws Exception {
if (StringUtils.isEmpty(obj)) {
return null;
}
Base64.Encoder encoder = Base64.getEncoder();
byte[] bytes = obj.getBytes("UTF-8");
return encoder.encodeToString(bytes);
}
}
注:
以上只展示核心代碼、其他次要代碼(例如redis配置、redis工具類等)可下載源碼查閱
2、使用防刷切面
在MyController 使用防刷
package com.zetting.modules.controller;
import com.zetting.aop.Prevent;
import com.zetting.common.Response;
import com.zetting.modules.dto.TestRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
/**
* 切面實(shí)現(xiàn)入?yún)⑿r?yàn)
*/
@RestController
public class MyController {
/**
* 測(cè)試防刷
*
* @param request
* @return
*/
@ResponseBody
@GetMapping(value = "/testPrevent")
@Prevent
public Response testPrevent(TestRequest request) {
return Response.success("調(diào)用成功");
}
/**
* 測(cè)試防刷
*
* @param request
* @return
*/
@ResponseBody
@GetMapping(value = "/testPreventIncludeMessage")
@Prevent(message = "10秒內(nèi)不允許重復(fù)調(diào)多次", value = "10")//value 表示10表示10秒
public Response testPreventIncludeMessage(TestRequest request) {
return Response.success("調(diào)用成功");
}
}3、演示

GIF.gif
gitee 源碼:https://gitee.com/Zetting/my-gather/tree/master/springboot-aop-prevent
到此這篇關(guān)于詳解Springboot如何通過(guò)注解實(shí)現(xiàn)接口防刷的文章就介紹到這了,更多相關(guān)Springboot接口防刷內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
springboot在idea下debug調(diào)試熱部署問(wèn)題
這篇文章主要介紹了springboot在idea下debug調(diào)試熱部署問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-02-02
java swing實(shí)現(xiàn)的掃雷游戲及改進(jìn)版完整示例
這篇文章主要介紹了java swing實(shí)現(xiàn)的掃雷游戲及改進(jìn)版,結(jié)合完整實(shí)例形式對(duì)比分析了java使用swing框架實(shí)現(xiàn)掃雷游戲功能與相關(guān)操作技巧,需要的朋友可以參考下2017-12-12
Springboot配置文件相關(guān)語(yǔ)法及讀取方式詳解
本文主要介紹了Spring Boot中的兩種配置文件形式,即.properties文件和.yml/.yaml文件,詳細(xì)講解了這兩種文件的語(yǔ)法和讀取方式,同時(shí),還介紹了使用@ConfigurationProperties注解和Environment接口讀取配置文件的方法,并提供了具體的讀取示例2025-12-12
Java8函數(shù)式接口UnaryOperator用法示例
這篇文章主要介紹了Java8函數(shù)式接口UnaryOperator用法示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-07
SpringBoot集成JWT實(shí)現(xiàn)token驗(yàn)證的流程
Json web token (JWT), 是為了在網(wǎng)絡(luò)應(yīng)用環(huán)境間傳遞聲明而執(zhí)行的一種基于JSON的開放標(biāo)準(zhǔn)((RFC 7519).這篇文章主要介紹了SpringBoot集成JWT實(shí)現(xiàn)token驗(yàn)證,需要的朋友可以參考下2020-01-01
Java原生服務(wù)器接收上傳文件 不使用MultipartFile類
這篇文章主要為大家詳細(xì)介紹了Java原生服務(wù)器接收上傳文件,不使用MultipartFile類,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-09-09
詳解Java中Array和ArrayList的比較和轉(zhuǎn)換
在 Java 編程中,arrays 和 arraylists 都是基本的數(shù)據(jù)結(jié)構(gòu),用來(lái)存放數(shù)據(jù)集合,雖然兩者的用途一樣,但是它們的特點(diǎn)極大地影響應(yīng)用的性能和靈活性,本文探討 arrays 和 arraylists 的重要特性,它們各自的強(qiáng)項(xiàng)和弱點(diǎn),,需要的朋友可以參考下2023-08-08
Java編程rabbitMQ實(shí)現(xiàn)消息的收發(fā)
RabbitMQ是一個(gè)在AMQP基礎(chǔ)上完成的,可復(fù)用的企業(yè)消息系統(tǒng),本文通過(guò)實(shí)例來(lái)給大家分享通過(guò)操作rabbitMQ實(shí)現(xiàn)消息的收發(fā),感興趣的朋友可以參考下。2017-09-09

