自定义注解实现防止重复提交

2022-03-12 11:20:52 浏览数 (1)

1,编写注解

创建注解FormResubmission类

代码语言:javascript复制
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface FormResubmission {
    /**
     * Redis过期时间 默认3s
     * @return
     */
    long expire() default 3;
}

2,编写切面实现类

代码语言:javascript复制
@Aspect
@Component
public class FormResubmissionAspect {

    @Autowired
    private RedisService redisService;

    @Autowired
    private HttpServletRequest request;

    @Pointcut("@annotation(com.beibo.annotation.FormResubmission)")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        String methodName = signature.getName();

        FormResubmission formResubmission = method.getAnnotation(FormResubmission.class);
        String redisKey = methodName   "_"   getToken(method);
        //  检查表单是否重复提交
        checkIsFormResubmit(redisKey);
        //  设置表单UUID到Redis
        addFormTagToRedis(formResubmission, redisKey);
        //  执行方法
        Object proceed = null;
        try {
            proceed = point.proceed();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        //         方法执行完毕,从Redis中移除设置的表单UUID
        redisService.del(redisKey);
        return proceed;
    }

    private void checkIsFormResubmit(String key) {
        if (redisService.hasKey(key)) {
            throw new CustomException("请勿重复提交!");
        }
    }

    private void addFormTagToRedis(FormResubmission formResubmission, String redisKey) {
        if (formResubmission != null) {
            redisService.set(redisKey, IdUtil.simpleUUID(), formResubmission.expire());
        }
    }

    private String getToken(Method method) {
        String token = null;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        token = authentication.getName();
        return token;
    }
}

3,完成

11

以上基本满足项目需要,暂时先这样处理。

腾云先锋(TDP,Tencent Cloud Developer Pioneer)是腾讯云GTS官方组建并运营的技术开发者群体。这里有最专业的开发者&客户,能与产品人员亲密接触,专有的问题&需求反馈渠道,有一群志同道合的兄弟姐妹。来加入属于我们开发者的社群吧!

0 人点赞