栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

实现基于 session+redis 的防重复提交

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

实现基于 session+redis 的防重复提交

实现基于 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 "";
    }

}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/946597.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号