SpringBoot接口防抖(防重复提交),接口幂等性,轻松搞定

📅 发布时间:2026/7/8 6:48:10 👁️ 浏览次数:
SpringBoot接口防抖(防重复提交),接口幂等性,轻松搞定
啥是防抖所谓防抖一是防用户手抖二是防网络抖动。在Web系统中表单提交是一个非常常见的功能如果不加控制容易因为用户的误操作或网络延迟导致同一请求被发送多次进而生成重复的数据记录。要针对用户的误操作前端通常会实现按钮的loading状态阻止用户进行多次点击。而对于网络波动造成的请求重发问题仅靠前端是不行的。为此后端也应实施相应的防抖逻辑确保在网络波动的情况下不会接收并处理同一请求多次。一个理想的防抖组件或机制我觉得应该具备以下特点逻辑正确也就是不能误判响应迅速不能太慢易于集成逻辑与业务解耦良好的用户反馈机制比如提示“您点击的太快了”什么是接口幂等性接口幂等性是指在分布式系统中对于相同的请求无论请求多少次都应该返回相同的结果。这意味着如果请求已经处理完毕那么重复请求应该返回相同的响应而不应该产生额外的副作用。这种特性对于确保系统的稳定性和一致性非常重要尤其是在处理并发请求和网络异常的情况下。在编程中可以通过一些特定的设计来实现接口幂等性例如使用全局唯一的ID来标记请求或者使用乐观锁机制来防止重复处理等。分布式部署下如何做接口防抖使用分布式锁流程图如下常见的分布式组件有Redis、Zookeeper等但结合实际业务来看一般都会选择Redis因为Redis一般都是Web系统必备的组件不需要额外搭建。具体实现现在有一个添加项目的接口/** * 添加项目 * param reqVO * return */ PostMapping(path /add) public ResultInteger queryScanCodeSwitch(RequestBody ProjectReqVO reqVO) { return Result.success(projectInfoService.createProject(reqVO)); }ProjectReqVO.javapackage com.example.springbootaopredis.dto; import lombok.Data; /** * 项目管理 新增 VO * */ Data public class ProjectReqVO { /** * 合同编号 */ private String contractNo; /** * 项目名字 */ private String name; /** * 项目状态 */ private Integer status; }幂等注解根据上面的要求我定义了一个注解Idempotent使用方式很简单把这个注解打在接口方法上即可。Idempotent.javapackage com.example.springbootaopredis.util; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.concurrent.TimeUnit; /** * Author: zcg * Description: 幂等注解 * Date: 2024/3/12 **/ Target({ElementType.METHOD}) Retention(RetentionPolicy.RUNTIME) public interface Idempotent { /** * 幂等的超时时间默认为 1 秒 * * 注意如果执行时间超过它请求还是会进来 */ int timeout() default 1; /** * 时间单位默认为 SECONDS 秒 */ TimeUnit timeUnit() default TimeUnit.SECONDS; /** * redis锁前缀 * return */ String keyPrefix() default idempotent; /** * key分隔符 * return */ String delimiter() default |; /** * 提示信息正在执行中的提示 */ String message() default 重复请求请稍后重试; }Idempotent 注解定义了几个基础的属性redis锁时间、redis锁时间单位、redis锁前缀、key分隔符、提示信息。其中前面三个参数比较好理解都是一个锁的基本信息。key分隔符是用来将多个参数合并在一起的比如name是测试项目contractNo是001那么完整的key就是测试项目|001最后再加上redis锁前缀就组成了一个唯一key。这里有些同学可能就要说了直接拿参数来生成key不就行了吗额不是不行但我想问一个问题如果这个接口参数有富文本你也打算把内容当做key吗要知道Redis的效率跟key的大小息息相关。所以我的建议是选取合适的字段作为key就行了没必要全都加上。要做到参数可选那么用注解的方式最好了注解如下RequestKeyParam.javapackage com.example.springbootaopredis.util; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * description 加上这个注解可以将参数设置为key */ Target({ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD}) Retention(RetentionPolicy.RUNTIME) Documented Inherited public interface RequestKeyParam { }这个注解加到参数上就行没有多余的属性。接下来就是lockKey的生成了代码如下RequestKeyGenerator.javapackage com.example.springbootaopredis.util; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.util.ReflectionUtils; import org.springframework.util.StringUtils; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Parameter; /** * Author: zcg * Description: 生成LockKey * Date: 2024/3/12 **/ public class RequestKeyGenerator { /** * 获取LockKey * * param joinPoint 切入点 * return */ public static String getLockKey(ProceedingJoinPoint joinPoint) { //获取连接点的方法签名对象 MethodSignature methodSignature (MethodSignature)joinPoint.getSignature(); //Method对象 Method method methodSignature.getMethod(); //获取Method对象上的注解对象 Idempotent idempotent method.getAnnotation(Idempotent.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(idempotent.delimiter()).append(args[i]); } //如果方法上没有加RequestKeyParam注解 if (StringUtils.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(idempotent.delimiter()).append(ReflectionUtils.getField(field, object)); } } } //返回指定前缀的key return idempotent.keyPrefix() sb; } }重复提交判断使用切面实现IdempotentAspect.javapackage com.example.springbootaopredis.util; import com.example.springbootaopredis.exception.CommonExcept; import lombok.extern.slf4j.Slf4j; 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 org.springframework.util.StringUtils; import java.lang.reflect.Method; /** * Author: zcg * Description: 幂等切面实现 * Date: 2024/3/12 **/ Aspect Configuration Order(2) Slf4j public class IdempotentAspect { private RedissonClient redissonClient; Autowired public IdempotentAspect(RedissonClient redissonClient) { this.redissonClient redissonClient; } Around(execution(public * * (..)) annotation(Idempotent)) public Object interceptor(ProceedingJoinPoint joinPoint) { MethodSignature methodSignature (MethodSignature)joinPoint.getSignature(); Method method methodSignature.getMethod(); Idempotent idempotent method.getAnnotation(Idempotent.class); if (StringUtils.isEmpty(idempotent.keyPrefix())) { throw new CommonExcept(重复提交前缀不能为空); } //获取自定义key final String lockKey RequestKeyGenerator.getLockKey(joinPoint); // 使用Redisson分布式锁的方式判断是否重复提交 RLock lock redissonClient.getLock(lockKey); boolean isLocked false; try { //尝试抢占锁 isLocked lock.tryLock(); //没有拿到锁说明已经有了请求了 if (!isLocked) { throw new CommonExcept(idempotent.message()); } //拿到锁后设置过期时间 lock.lock(idempotent.timeout(), idempotent.timeUnit()); try { return joinPoint.proceed(); } catch (Throwable throwable) { log.info(系统异常, throwable); throw new CommonExcept(系统异常 throwable.getMessage()); } } catch (Exception e) { throw new CommonExcept(e.getMessage()); } finally { //释放锁 if (isLocked lock.isHeldByCurrentThread()) { lock.unlock(); } } } }Redisson的核心思路就是抢锁当一次请求抢到锁之后对锁加一个过期时间在这个时间段内重复的请求是无法获得这个锁也不难理解。接下来测试一下第一次提交成功短时间内重复提交过几秒后再次提交添加成功本文介绍了使用springboot和切面、redis来优雅的实现接口幂等对于幂等在实际的开发过程中是十分重要的因为一个接口可能会被无数的客户端调用如何保证其不影响后台的业务处理如何保证其只影响数据一次是非常重要的它可以防止产生脏数据或者乱数据也可以减少并发量实乃十分有益的一件事。而传统的做法是每次判断数据这种做法不够智能化和自动化比较麻烦。而今天的这种自动化处理也可以提升程序的伸缩性。