自定义注解使用之后端实现防重复提交(后端幂等)

业务背景:后端实现前端防止重复提交

常规思路:自定义一个注解,在需要用到的注解的方法上加上即可,aop会自动扫描该注解并执行切面逻辑

1.自定义注解代码如下:

 2.定义切面逻辑如下:

 

 @Resource
    private RedissonClient redissonClient;

    /**
     * 防止表单重复提交
     * @param joinPoint 切入点
     * @return
     */
    @Around("@annotation(NoRepeat)")
    public Object aroundUnRepeat(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取token
        String token = WebUtils.getToken(((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
        if(StringUtils.isEmpty(token)){
            return joinPoint.proceed();
        }
        //解析方法
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = method.getName();
        Object result = null;
        //获取分布式锁 lock+redissession
        RLock lock = redissonClient.getLock(buildKey(className, methodName, token));
        if(lock.isLocked()){
            //如果已经被锁,则网络繁忙,要求用户重新刷新
            throw new BaseRuntimeException(CommonResultCode.NETWORK_BUSY);
        }
        try {
            lock.tryLock(1,1, TimeUnit.SECONDS);
            result = joinPoint.proceed();
        } finally {
            if(lock.isLocked()){
                if (lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        }
        return result;
    }

    /**
     * 防止重复提交的key com.hkbt.test.Test:test:jslfignsowetn
     * @param fullClassName
     * @param methodName
     * @param token
     * @return
     */
    private String buildKey(String fullClassName,String methodName,String token){
        return fullClassName + AnnoConstant._M + methodName + AnnoConstant._M + token;
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值