日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

實現基于 session+redis 的防重復提交

作者:友發小猿 更新時間: 2022-07-13 編程語言

實現基于 session+redis 的防重復提交
?? ?? ?? ?? gitee源碼倉庫????????

1、定義注解

package cn.springboot.model.base.annotation;

import java.lang.annotation.*;

/**
 * 自定義注解防止表單重復提交
 * @author k
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface Submit {
    String prefix() default "prefix:";

    /**
     * 秒
     *
     * @return
     */
    long lockTime() default 10;
}


2、實現 aop 切面

/**
 * 重復提交aop切面
 *
 * @author k
 */
@Aspect
@Component
public class SubmitAspect {

    @Autowired
    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 (StringUtils.isNotNull(key)) {
            //讀取緩存
            if (redisUtils.string.get(key) != null) {
                Long expire = redisUtils.common.getExpire(key);
                String message = GlobalExceptionEnum.REPEAT_SUBMIT.getMessage();
                throw new GlobalException(GlobalExceptionEnum.REPEAT_SUBMIT.getCode(), message + ",請" + expire + "秒后重試!");
            }
            // 如果是第一次請求,就將key存入緩存中
            redisUtils.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 "";
    }

}


原文鏈接:https://blog.csdn.net/qq_42476834/article/details/125103877

欄目分類
最近更新