自定义防重提交
1. 自定义注解
import java.lang.annotation.*;
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RepeatSubmit {
Type limitType() default Type.PARAM;
long lockTime() default 5;
int maxCount() default 1;
String msg() default "操作频率过高";
enum Type {
PARAM(1, "方法参数"), TOKEN(2, "令牌");
private int id;
private String name;
Type() {
}
Type(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return this.name;
}
}
boolean needLogin() default false;
}
2. 基于环绕通知实现限流锁
import cn.hutool.extra.servlet.ServletUtil;
import com.qihoo.mssosservice.annotation.RepeatSubmit;
import com.qihoo.mssosservice.constants.Constants;
import com.qihoo.mssosservice.model.resp.RestfulResult;
import com.redxun.common.utils.ContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
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.DigestUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
@Aspect
@Component
@Slf4j
public class RepeatSubmitAspect {
@Autowired
private StringRedisTemplate redisTemplate;
@Pointcut("@annotation(repeatSubmit)")
public void pointCutNoRepeatSubmit(RepeatSubmit repeatSubmit) {
}
@Around("pointCutNoRepeatSubmit(repeatSubmit)")
public Object around(ProceedingJoinPoint joinPoint, RepeatSubmit repeatSubmit) throws Throwable {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String accountNo = ObjectUtils.isEmpty(ContextUtil.getCurrentUser()) ? "admin" : ContextUtil.getCurrentUser().getAccount();
boolean res = false;
long lockTime = repeatSubmit.lockTime();
int maxCount = repeatSubmit.maxCount();
String msg = repeatSubmit.msg();
String type = repeatSubmit.limitType().name();
boolean needLogin = repeatSubmit.needLogin();
if (needLogin) {
String authorization = request.getHeader("Authorization");
if (StringUtils.isBlank(authorization )) {
authorization = request.getParameter("Authorization");
}
if (StringUtils.isBlank(authorization)) {
return RestfulResult.getFailResult("没有登录");
}
}
if (type.equalsIgnoreCase(RepeatSubmit.Type.PARAM.name())) {
String ipAddr = ServletUtil.getClientIP(request, null);
String requestURI = request.getRequestURI();
MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature();
Method method = methodSignature.getMethod();
String className = method.getDeclaringClass().getName();
String key = Constants.SUBMIT_ORDER_REPEAT_SUBMIT+ DigestUtils.md5DigestAsHex(String.format("%s-%s-%s-%s-%s",ipAddr,requestURI,className,method,accountNo).getBytes(StandardCharsets.UTF_8));
String count = redisTemplate.opsForValue().get(key);
if (StringUtils.isBlank(count)) {
res = redisTemplate.opsForValue().setIfAbsent(key, "1", lockTime, TimeUnit.SECONDS);
} else {
if (Integer.valueOf(count) > maxCount) {
return RestfulResult.getFailResult(msg);
} else {
redisTemplate.opsForValue().increment(key);
}
}
} else if (type.equalsIgnoreCase(RepeatSubmit.Type.TOKEN.name())) {
String authorization = request.getHeader("Authorization");
if (StringUtils.isBlank(authorization )) {
authorization = request.getParameter("Authorization");
}
if (StringUtils.isBlank(authorization)) {
return RestfulResult.getFailResult("没有登录");
}
String key = String.format(Constants.SUBMIT_ORDER_REPEAT_TOKEN_KEY, authorization, accountNo);
String count = redisTemplate.opsForValue().get(key);
if (StringUtils.isBlank(count)) {
res = redisTemplate.opsForValue().setIfAbsent(key, "1", lockTime, TimeUnit.SECONDS);
} else {
if (Integer.valueOf(count) > maxCount) {
return RestfulResult.getFailResult(msg);
} else {
redisTemplate.opsForValue().increment(key);
}
}
} else {
return RestfulResult.getFailResult(type+":未定义的类型!");
}
if (!res) {
log.error("请求重复提交");
return RestfulResult.getFailResult("请求重复提交");
}
log.info("环绕通知执行前");
Object obj = joinPoint.proceed();
log.info("环绕通知执行后");
return obj;
}
}
3. 使用 示例
@RepeatSubmit
@GetMapping("/getAllURL")
public RestfulResult getAllURL() {
return RestfulResult.getSuccessResult(result);
}
@RepeatSubmit(limitType =RepeatSubmit.Type.PARAM,lockTime=10,maxCount=2,msg = "test",needLogin = true)
@GetMapping("/getAllURL")
public RestfulResult getAllURL() {
return RestfulResult.getSuccessResult(result);
}