SpringBoot 使用注解解决接口防刷

@Documented
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Prevent {
    int seconds() default 60;
    int maxCount() default 1;
    String message() default "";
}
import cn.hutool.json.JSONUtil;
import com.boot.common.BusinessException;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.concurrent.TimeUnit;

/**
 * 防刷切面实现类
 */
@Aspect
@Component
public class PreventAop {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Pointcut("@annotation(com.boot.aop.Prevent)")
    public void pointcut() {
    }

    @Before("pointcut()")
    public void joinPoint(JoinPoint joinPoint) throws Exception {
        String requestStr = JSONUtil.toJsonStr(joinPoint.getArgs()[0]);
        if (StringUtils.isEmpty(requestStr) || requestStr.equalsIgnoreCase("{}")) {
            throw new BusinessException("[防刷]入参不允许为空");
        }

        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();

        defaultHandle(requestStr, preventAnnotation, methodFullName);
    }

    private void defaultHandle(String requestStr, Prevent prevent, String methodFullName) throws Exception {
        String base64Str = toBase64String(requestStr);
        int expire = prevent.seconds();
        int maxCount = prevent.maxCount();
        String resp = redisTemplate.opsForValue().get(methodFullName + base64Str);
        int count = StringUtils.isEmpty(resp) ? 0 : Integer.parseInt(resp);
        if (StringUtils.isEmpty(resp)) {
            redisTemplate.opsForValue().set(methodFullName + base64Str, "1", expire, TimeUnit.SECONDS);
        } else if (count < maxCount) {
            redisTemplate.opsForValue().increment(methodFullName + base64Str);
        } 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(StandardCharsets.UTF_8);
        return encoder.encodeToString(bytes);
    }

}
/**
 * 基础响应码
 */
public class BusinessCode {
    //--------成功------------
    public static final BusinessCode SUCCESS = new BusinessCode("success", "操作成功");

    //--------失败------------
    public static final BusinessCode FAIL = new BusinessCode("fail", "系统异常");
    public static final BusinessCode EXCEPTION = new BusinessCode("exception", "未知异常");
    public static final BusinessCode PARAM_ILLEGAL = new BusinessCode("param_illegal", "参数不合法");
    public static final BusinessCode PARAM_EMPTY = new BusinessCode("param_empty", "入参为空");

    private String code;

    private String msg;


    public BusinessCode(String code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public BusinessCode(BusinessCode businessCode) {
        this.code = businessCode.getCode();
        this.msg = businessCode.getMsg();
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}
/**
 * 基础业务异常类
 */
public class BusinessException extends RuntimeException{
    private String code;
    private String msg;
    private Throwable cause;
    public BusinessException(){

    }

    public BusinessException(String msg) {
        super(msg);
        this.setCode(BusinessCode.FAIL.getCode());
        this.setMsg(msg);
    }

    public BusinessException(BusinessCode businessCode) {
        super(businessCode.getMsg());
        this.setCode(businessCode.getCode());
        this.setMsg(businessCode.getMsg());
    }

    public BusinessException(String msg, Throwable e) {
        super(msg);
        this.setCode(BusinessCode.FAIL.getCode());
        this.setMsg( msg);
        this.cause = e;
    }

    public BusinessException(BusinessCode businessCode, String msg) {
        super(msg);
        this.setCode(businessCode.getCode());
        this.setMsg(msg);
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    @Override
    public Throwable getCause() {
        return cause;
    }
}
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * 全局异常捕获
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private final Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * 入参非法异常捕获
     *
     * @param e
     * @return
     */
    @ExceptionHandler({BusinessException.class})
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Response handleServiceException(BusinessException e) {
        log.error("系统异常", e);
        BusinessCode code = new BusinessCode(e.getCode(), e.getMsg());
        return Response.fail(code, e.getMsg());
    }


    /**
     * 系统异常捕获
     *
     * @param e
     * @return
     */
    @ExceptionHandler({Exception.class})
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Response handleOtherException(Exception e) {
        log.error("系统异常", e);
        return Response.fail(BusinessCode.EXCEPTION, "系统异常");
    }

}
import java.io.Serializable;

/**
 * 返回数据
 */
public class Response<T> implements Serializable {
    private static final long serialVersionUID = 1L;
    /**
     * 响应业务状态
     */
    private String code;

    /**
     * 响应消息
     */
    private String msg;

    /**
     * 响应中的数据
     */
    private transient T data;

    private Response() {
    }

    public Response(String code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public static Response init(BusinessCode respCode, String msg) {
        Response response = new Response();
        response.setCode(respCode.getCode());
        response.setMsg(msg);
        return response;
    }

    public static <T> Response init(BusinessCode respCode, String msg, T data) {
        Response response = new Response();
        response.setCode(respCode.getCode());
        response.setMsg(msg);
        response.setData(data);
        return response;
    }

    public static <T> Response init(String code, String msg, T data) {
        Response response = new Response();
        response.setCode(code);
        response.setMsg(msg);
        response.setData(data);
        return response;
    }

    public static Response success() {
        return init(BusinessCode.SUCCESS, BusinessCode.SUCCESS.getMsg());
    }

    public static Response success(String msg) {
        return init(BusinessCode.SUCCESS, msg);
    }

    public static Response success(Object data, String msg) {
        return init(BusinessCode.SUCCESS, msg, data);
    }

    public static Response fail(BusinessCode respCode, String msg) {
        return init(respCode, msg);
    }

    public static Response fail() {
        return init(BusinessCode.FAIL, BusinessCode.FAIL.getMsg());
    }

    public static Response fail(String msg) {
        return init(BusinessCode.FAIL, msg);
    }

    public static boolean isSuccess(Response response) {
        return BusinessCode.SUCCESS.getCode() == response.getCode();
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}

import com.boot.aop.Prevent;
import com.boot.common.Response;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 切面实现入参校验
 */
@RestController
public class MyController {

    @GetMapping(value = "/testPrevent")
    @Prevent(maxCount = 5)
    public Response testPrevent(String mobile) {
        return Response.success("调用成功");
    }

}

一个注解搞定 Spring Boot 接口防刷

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值