前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >自定义注解实现防止重复提交

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

原创
作者头像
无敌小菜鸟
发布2022-03-12 11:20:52
1.1K1
发布2022-03-12 11:20:52
举报
文章被收录于专栏:搬砖笔记搬砖笔记

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,完成

1
1

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

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

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1,编写注解
  • 2,编写切面实现类
  • 3,完成
相关产品与服务
云数据库 Redis
腾讯云数据库 Redis(TencentDB for Redis)是腾讯云打造的兼容 Redis 协议的缓存和存储服务。丰富的数据结构能帮助您完成不同类型的业务场景开发。支持主从热备,提供自动容灾切换、数据备份、故障迁移、实例监控、在线扩容、数据回档等全套的数据库服务。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档