防重复提交问题å‘处理

This commit is contained in:
Chopper711 2022-10-28 17:58:28 +08:00
parent 5a14790ec2
commit ca23b5ab33
2 changed files with 45 additions and 14 deletions

View File

@ -18,7 +18,12 @@ public @interface PreventDuplicateSubmissions {
/**
* 过期时间
* 过期时间 默认3秒即3秒内无法重复点击
*/
long expire() default 3;
/**
* 用户间隔离默认false
* 如果为true则全局限制为true需要用户登录状态否则则是全局隔离
*/
boolean userIsolation() default false;
}

View File

@ -1,9 +1,19 @@
package cn.lili.common.aop.interceptor;
/**
* 防重复提交业务
*
* @author Chopper
* @version v1.0
* 2022-01-25 09:20
*/
import cn.hutool.json.JSONUtil;
import cn.lili.cache.Cache;
import cn.lili.common.aop.annotation.PreventDuplicateSubmissions;
import cn.lili.common.enums.ResultCode;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.security.AuthUser;
import cn.lili.common.security.context.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
@ -15,13 +25,6 @@ import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
/**
* 防重复提交业务
*
* @author Chopper
* @version v1.0
* 2022-01-25 09:20
*/
@Aspect
@Component
@Slf4j
@ -35,9 +38,11 @@ public class PreventDuplicateSubmissionsInterceptor {
public void interceptor(PreventDuplicateSubmissions preventDuplicateSubmissions) {
try {
Long count = cache.incr(getParams(), preventDuplicateSubmissions.expire());
//如果超过2或者设置的参数则表示重复提交了
if (count.intValue() >= 2) {
String redisKey = getParams(preventDuplicateSubmissions.userIsolation());
Long count = cache.incr(redisKey, preventDuplicateSubmissions.expire());
log.debug("防重复提交params-{},value-{}", redisKey, count);
//如果超过0或者设置的参数则表示重复提交了
if (count.intValue() > 0) {
throw new ServiceException(ResultCode.LIMIT_ERROR);
}
}
@ -55,12 +60,33 @@ public class PreventDuplicateSubmissionsInterceptor {
/**
* 获取表单参数
*
* @return
* @param userIsolation 用户是否隔离
* @return 计数器key
*/
private String getParams() {
private String getParams(Boolean userIsolation) {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
StringBuilder stringBuilder = new StringBuilder();
//拼接请求地址
stringBuilder.append(request.getRequestURI());
//参数不为空则拼接参数
if (!request.getParameterMap().isEmpty()) {
stringBuilder.append(JSONUtil.toJsonStr(request.getParameterMap()));
}
//用户隔离设置为开启则选择当前用回顾
if (userIsolation) {
AuthUser authUser = UserContext.getCurrentUser();
//用户为空则发出警告但不拼接否则拼接用户id
if (authUser == null) {
log.warn("user isolation settings are on,but current user is null");
}
// 不为空则拼接用户id
else {
stringBuilder.append(authUser.getId());
}
}
//请求地址
return request.getRequestURI() + UserContext.getCurrentUser().getId() + UserContext.getCurrentUser().getUsername();
return stringBuilder.toString();
}