@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);
}
}
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());
@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());
}
@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 接口防刷