实现基于 session+redis 的防重复提交
gitee源码仓库
1、定义注解
package cn.springboot.model.base.annotation;
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface Submit {
String prefix() default "prefix:";
long lockTime() default 10;
}
2、实现 aop 切面
@Aspect
@Component
public class SubmitAspect {
@Resource
private RedisUtils redisUtils;
@Pointcut("execution(public * *(..)) && @annotation(cn.springboot.model.base.annotation.Submit)")
public void submitPointCut() {
}
@Around("submitPointCut()")
public Object interceptor(ProceedingJoinPoint joinPoint) throws Throwable {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
String sessionId = RequestContextHolder.getRequestAttributes().getSessionId();
HttpServletRequest request = attributes.getRequest();
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
Submit submit = method.getAnnotation(Submit.class);
//设置key: prefix:sessionId-Path-method+参数
String key = submit.prefix() + sessionId + ":" + request.getServletPath() + ":" + method.getName() + ":" + getArgs(joinPoint);
if (!Objects.isNull(key)) {
//读取缓存
if (redisUtils.new String().get(key) != null) {
Long expire = redisUtils.new Common().getExpire(key);
String message = GlobalExceptionEnum.REPEAT_SUBMIT.getMessage();
throw new GlobalException(GlobalExceptionEnum.REPEAT_SUBMIT.getCode(), message + ",请" + expire + "秒后重试!");
}
// 如果是第一次请求,就将key存入缓存中
redisUtils.new String().set(key, key, submit.lockTime());
}
return joinPoint.proceed();
}
private String getArgs(ProceedingJoinPoint joinPoint) {
Object[] args = joinPoint.getArgs();
boolean argsStatus = StringUtils.isNotNull(args);
if (argsStatus) {
StringBuilder data = new StringBuilder();
for (Object o : Arrays.stream(args).toArray()) {
data.append(o);
}
return data.toString();
}
return "";
}
}



