Redission分布式锁实现接口幂等性

Redission分布式锁实现接口幂等性

1. 何为接口幂等性

接口幂等性(Idempotence)指的是一个接口在相同的条件下,无论被调用多少次,其产生的效果都与一次调用相同。查询接口不涉及幂等性的问题,新增、更新、删除都可能会涉及接口幂等性问题,具体情况因业务而已

用户多次点击或网络故障都有可能造成接口幂等性问题,这个时候就需要前端增加防抖动功能,后端增加接口的幂等性校验,做到双重防护

2. Redisson实现接口幂等性的流程

关键步骤:

  1. 根据接口关键参数生成分布式锁的key
  2. 根据生成的分布式锁的key获取分布式锁
  3. 分布式锁获取成功,接着设置key的过期时间(很重要),设置成功之后执行接口的业务逻辑;分布式锁获取失败,抛出操作频繁的异常提示

3. Redisson实现接口幂等性的具体实现

前提是集成了redission的环境Spring Boot集成Redisson

  • 定义标记接口的幂等性的注解
package com.jiayuan.common.annotation;

import java.lang.annotation.*;
import java.util.concurrent.TimeUnit;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface RequestLock {

    /**
     * redis锁前级(接口方法名)
     */
    String prefix() default "";

    /**
     * redis锁过期时间 默认2秒
     */
    int expire() default 2;

    /**
     * redis锁过期时间单位默认学位为秘
     */
    TimeUnit timeUnit() default TimeUnit.SECONDS;

    /**
     * redis key分隔符
     */
    String delimiter() default "@";
}
  • 定义标记接口关键参数的注解,用于组成分布式锁的key
package com.jiayuan.common.annotation;

import java.lang.annotation.*;

@Target({ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface RequestKeyParam {

}
  • 定义幂等性校验的切面
package com.jiayuan.common.aspect;

import cn.hutool.core.util.StrUtil;
import com.jiayuan.common.annotation.RequestLock;
import com.jiayuan.common.enums.ErrorCode;
import com.jiayuan.common.exception.BizException;
import com.jiayuan.common.utils.RequestKeyGenerator;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import java.lang.reflect.Method;


@Aspect
@Configuration
@Order(2)
public class RedissonRequestLockAspect {
    private RedissonClient redissonClient;

    @Autowired
    public RedissonRequestLockAspect(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    /**
     * 通过环绕通知的方式,使用Redisson实现方法级别的分布式锁,以防止并发重复提交问题。
     * 该方法主要通过自定义注解RequestLock来标识需要加锁的方法,通过Redisson的锁机制保证同一业务逻辑的同一用户操作不会被重复执行。
     *
     * @param joinPoint 切入点对象,用于获取方法签名和执行方法
     * @return 被拦截方法的返回值
     * @throws BizException 业务异常,主要处理重复提交和锁的异常情况
     */
    @Around("execution(public * * (..)) && @annotation(com.jiayuan.common.annotation.RequestLock)")
    public Object interceptor(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        RequestLock requestLock = method.getAnnotation(RequestLock.class);
        if (StrUtil.isEmpty(requestLock.prefix())) {
            throw new BizException(ErrorCode.BIZ_CHECK_FAIL, "重复提交前缀不能为空");
        }

        // 获取自定义key
        final String lockKey = RequestKeyGenerator.getLockKey(joinPoint);
        // 使用Redisson分布式锁的方式判断是否重复提交
        RLock lock = redissonClient.getLock(lockKey);
        boolean isLocked = false;
        try {
            // 尝试抢占锁,指定等待时间和锁的持有时间
            isLocked = lock.tryLock();

            // 如果没有拿到锁
            if (!isLocked) {
                throw new BizException(ErrorCode.BIZ_CHECK_FAIL, "您的操作太快了,请稍后重试");
            }

            //拿到锁后设置过期时间
            lock.lock(requestLock.expire(), requestLock.timeUnit());

            // 执行被拦截的方法
            return joinPoint.proceed();
        } catch (Exception e) {
            // 重新抛出业务异常或中断异常
            throw e;
        } catch (Throwable throwable) {
            // 抛出自定义异常并携带原始异常
            throw new Exception("幂等性校验错误", throwable);
        } finally {
            // 释放锁
            if (isLocked && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }

}

  • 定义生成分布式锁key的工具
package com.jiayuan.common.utils;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

import cn.hutool.core.util.StrUtil;
import com.jiayuan.common.annotation.RequestKeyParam;
import com.jiayuan.common.annotation.RequestLock;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;


public class RequestKeyGenerator {
    /**
     * 获取LockKey
     *
     * @param joinPoint 切入点
     * @return
     */
    public static String getLockKey(ProceedingJoinPoint joinPoint) {
        //获取连接点的方法签名对象
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        //Method对象
        Method method = methodSignature.getMethod();
        //获取Method对象上的注解对象
        RequestLock requestLock = method.getAnnotation(RequestLock.class);
        //获取方法参数
        final Object[] args = joinPoint.getArgs();
        //获取Method对象上所有的注解
        final Parameter[] parameters = method.getParameters();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < parameters.length; i++) {
            final RequestKeyParam keyParam = parameters[i].getAnnotation(RequestKeyParam.class);
            //如果属性不是RequestKeyParam注解,则不处理
            if (keyParam == null) {
                continue;
            }
            //如果属性是RequestKeyParam注解,则拼接 连接符 "& + RequestKeyParam"
            sb.append(requestLock.delimiter()).append(args[i]);
        }
        //如果方法上没有加RequestKeyParam注解
        if (StrUtil.isEmpty(sb.toString())) {
            //获取方法上的多个注解(为什么是两层数组:因为第二层数组是只有一个元素的数组)
            final Annotation[][] parameterAnnotations = method.getParameterAnnotations();
            //循环注解
            for (int i = 0; i < parameterAnnotations.length; i++) {
                final Object object = args[i];
                //获取注解类中所有的属性字段
                final Field[] fields = object.getClass().getDeclaredFields();
                for (Field field : fields) {
                    //判断字段上是否有RequestKeyParam注解
                    final RequestKeyParam annotation = field.getAnnotation(RequestKeyParam.class);
                    //如果没有,跳过
                    if (annotation == null) {
                        continue;
                    }
                    //如果有,设置Accessible为true(为true时可以使用反射访问私有变量,否则不能访问私有变量)
                    field.setAccessible(true);
                    //如果属性是RequestKeyParam注解,则拼接 连接符" & + RequestKeyParam"
                    sb.append(requestLock.delimiter()).append(ReflectionUtils.getField(field, object));
                }
            }
        }
        //返回指定前缀的key
        return requestLock.prefix() + sb;
    }
}


  • 接口使用示例
@PostMapping("report")
@ApiOperation("数据上报")
@LogOperation(value = "数据上报")
@RequestLock(prefix = "cvReport")
public Result report(@RequestBody @Validated(value = DefaultGroup.class) ReportDTO dto) {
    final CVAction action = dto.getAction();
    reportHandlerFactory.getHandler(action).handle(dto);
    return Result.ok();
}
  • 演示结果

第一次点击

第二次快速点击,或者连续多点击几次

4. 参考和感谢

SpringBoot接口防抖(防重复提交)的一些实现方案

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值