詳解Springboot如何通過注解實現(xiàn)接口防刷
前言
本文介紹一種極簡潔、靈活通用接口防刷實現(xiàn)方式、通過在需要防刷的方法加上@Prevent 注解即可實現(xiàn)短信防刷;
使用方式大致如下:
/**
* 測試防刷
*
* @param request
* @return
*/
@ResponseBody
@GetMapping(value = "/testPrevent")
@Prevent //加上該注解即可實現(xiàn)短信防刷(默認一分鐘內不允許重復調用,支持擴展、配置)
public Response testPrevent(TestRequest request) {
return Response.success("調用成功");
}
1、實現(xiàn)防刷切面PreventAop.java
大致邏輯為:定義一切面,通過@Prevent注解作為切入點、在該切面的前置通知獲取該方法的所有入?yún)⒉⑵銪ase64編碼,將入?yún)ase64編碼+完整方法名作為redis的key,入?yún)⒆鳛閞eids的value,@Prevent的value作為redis的expire,存入redis;每次進來這個切面根據(jù)入?yún)ase64編碼+完整方法名判斷redis值是否存在,存在則攔截防刷,不存在則允許調用;
1.1 定義注解Prevent
package com.zetting.aop;
import java.lang.annotation.*;
/**
* 接口防刷注解
* 使用:
* 在相應需要防刷的方法上加上
* 該注解,即可
*
* @author: zetting
* @date:2018/12/29
*/
@Documented
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Prevent {
/**
* 限制的時間值(秒)
*
* @return
*/
String value() default "60";
/**
* 提示
*/
String message() default "";
/**
* 策略
*
* @return
*/
PreventStrategy strategy() default PreventStrategy.DEFAULT;
}
1.2 實現(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;
/**
* 防刷切面實現(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;
/**
* 切入點
*/
@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("無效的策略");
}
}
/**
* 默認處理方式
*
* @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 + "秒內不允許重復請求";
throw new BusinessException(message);
}
}
/**
* 對象轉換為base64字符串
*
* @param obj 對象值
* @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;
/**
* 切面實現(xiàn)入?yún)⑿r?
*/
@RestController
public class MyController {
/**
* 測試防刷
*
* @param request
* @return
*/
@ResponseBody
@GetMapping(value = "/testPrevent")
@Prevent
public Response testPrevent(TestRequest request) {
return Response.success("調用成功");
}
/**
* 測試防刷
*
* @param request
* @return
*/
@ResponseBody
@GetMapping(value = "/testPreventIncludeMessage")
@Prevent(message = "10秒內不允許重復調多次", value = "10")//value 表示10表示10秒
public Response testPreventIncludeMessage(TestRequest request) {
return Response.success("調用成功");
}
}3、演示

GIF.gif
gitee 源碼:https://gitee.com/Zetting/my-gather/tree/master/springboot-aop-prevent
到此這篇關于詳解Springboot如何通過注解實現(xiàn)接口防刷的文章就介紹到這了,更多相關Springboot接口防刷內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
解決java調用dll報Unable to load library錯誤的問題
這篇文章主要介紹了解決java調用dll報Unable to load library錯誤的問題。具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11
Mybatis-plus的selectPage()分頁查詢不生效問題解決
本文主要介紹了Mybatis-plus的selectPage()分頁查詢不生效問題解決,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-01-01
Java利用MultipartFile實現(xiàn)上傳多份文件的代碼
這篇文章主要介紹了Java利用MultipartFile實現(xiàn)上傳多份文件的代碼,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2019-09-09

