通过Aop进行防止重复提交, 把 pds-sessionId-请求路径作为请求的唯一key,用户发送请求时,判断key是否存在,如果存在则重复提交,不存在,则进行保存,执行完后或者出现异常进行清除。
key 超时5秒自动清除
一.自定义注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 防止重复提交标记注解
*
* @author liuqiyu
*/
@Target(ElementType.METHOD) // 作用到方法上
@Retention(RetentionPolicy.RUNTIME) // 运行时有效
public @interface PreventDuplicateSubmit {
}
二.定义AOP 进行处理
import com.qike.base.PreventDuplicateSubmit;
import com.qike.exception.GlobalRuntimeException;
import com.qike.security.session.RedisCacheManager;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
/**
* 防止重复提交切面
*
* @author: liuqiyu
* @date: 2021/1/13
* @version: 1.0
*/
@Slf4j
@Aspect
@Component
public class PreventDuplicateSubmitAop {
@Autowired
RedisCacheManager redisCacheManager;
@Pointcut("execution(public * com.qike..*.*(..))")
public void preventDuplicateSubmit() {
}
@Around("preventDuplicateSubmit() && @annotation(pds)")
public Object around(ProceedingJoinPoint pjp, PreventDuplicateSubmit pds) throws Throwable {
log.info("进行防重复提交");
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
String sessionId = Objects.requireNonNull(RequestContextHolder.getRequestAttributes()).getSessionId();
HttpServletRequest request = attributes.getRequest();
String key = "pds-" + sessionId + "-" + request.getServletPath();
// 如果缓存中有这个url视为重复提交
if (redisCacheManager.get(key) == null) {
redisCacheManager.set(key, "0",5);
Object o = pjp.proceed();
redisCacheManager.del(key);
return o;
} else {
log.error("重复提交");
throw new GlobalRuntimeException(300,"重复提交");
}
}
@AfterThrowing(pointcut = "preventDuplicateSubmit() && @annotation(pds)", throwing = "e")
public void doAfterThrowing(Throwable e, PreventDuplicateSubmit pds) {
log.error("异常解除防重复提交");
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
String sessionId = Objects.requireNonNull(RequestContextHolder.getRequestAttributes()).getSessionId();
HttpServletRequest request = attributes.getRequest();
String key = "pds-" + sessionId + "-" + request.getServletPath();
redisCacheManager.del(key);
}
}