百度 网站速度诊断,广西建设网站在线服务,星座 网站 建设,学校网站建设计划一、前言作为一名从业已达六年的老码农#xff0c;我的工作主要是开发后端Java业务系统#xff0c;包括各种管理后台和小程序等。在这些项目中#xff0c;我设计过单/多租户体系系统#xff0c;对接过许多开放平台#xff0c;也搞过消息中心这类较为复杂的应用#xff0c…一、前言作为一名从业已达六年的老码农我的工作主要是开发后端Java业务系统包括各种管理后台和小程序等。在这些项目中我设计过单/多租户体系系统对接过许多开放平台也搞过消息中心这类较为复杂的应用但幸运的是我至今还没有遇到过线上系统由于代码崩溃导致资损的情况。这其中的原因有三点一是业务系统本身并不复杂二是我一直遵循某大厂代码规约在开发过程中尽可能按规约编写代码三是经过多年的开发经验积累我成为了一名熟练工掌握了一些实用的技巧。二、啥是防抖所谓防抖一是防用户手抖二是防网络抖动。在Web系统中表单提交是一个非常常见的功能如果不加控制容易因为用户的误操作或网络延迟导致同一请求被发送多次进而生成重复的数据记录。 要针对用户的误操作前端通常会实现按钮的loading状态阻止用户进行多次点击。而对于网络波动造成的请求重发问题仅靠前端是不行的。为此后端也应实施相应的防抖逻辑确保在网络波动的情况下不会接收并处理同一请求多次。一个理想的防抖组件或机制我觉得应该具备以下特点逻辑正确也就是不能误判响应迅速不能太慢易于集成逻辑与业务解耦良好的用户反馈机制比如提示“您点击的太快了”三、思路解析前面讲了那么多我们已经知道接口的防抖是很有必要的了但是在开发之前我们需要捋清楚几个问题。1. 哪一类接口需要防抖?接口防抖也不是每个接口都需要加一般需要加防抖的接口有这几类用户输入类接口比如搜索框输入、表单输入等用户输入往往会频繁触发接口请求但是每次触发并不一定需要立即发送请求可以等待用户完成输入一段时间后再发送请求。按钮点击类接口比如提交表单、保存设置等用户可能会频繁点击按钮但是每次点击并不一定需要立即发送请求可以等待用户停止点击一段时间后再发送请求。滚动加载类接口比如下拉刷新、上拉加载更多等用户可能在滚动过程中频繁触发接口请求但是每次触发并不一定需要立即发送请求可以等待用户停止滚动一段时间后再发送请求。2. 如何确定接口是重复的防抖也即防重复提交那么如何确定两次接口就是重复的呢首先我们需要给这两次接口的调用加一个时间间隔大于这个时间间隔的一定不是重复提交其次两次请求提交的参数比对不一定要全部参数选择标识性强的参数即可最后如果想做的更好一点还可以加一个请求地址的对比。3. 分布式部署下如何做接口防抖有两个方案1使用共享缓存流程图如下2使用分布式锁流程图如下常见的分布式组件有Redis、Zookeeper等但结合实际业务来看一般都会选择Redis因为Redis一般都是Web系统必备的组件不需要额外搭建。四、具体实现现在有一个保存用户的接口PostMapping(/add) RequiresPermissions(value add) Log(methodDesc 添加用户) public ResponseEntityString add(RequestBody AddReq addReq) { return userService.add(addReq); }**AddReq.java **package com.summo.demo.model.request; import java.util.List; import lombok.Data; Data publicclass AddReq { /** * 用户名称 */ private String userName; /** * 用户手机号 */ private String userPhone; /** * 角色ID列表 */ private ListLong roleIdList; }目前数据库表中没有对userPhone字段做UK索引这就会导致每调用一次add就会创建一个用户即使userPhone相同。1. 请求锁根据上面的要求我定了一个注解RequestLock使用方式很简单把这个注解打在接口方法上即可。RequestLock.javaimport 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; import java.util.concurrent.TimeUnit; /** * description 请求防抖锁用于防止前端重复提交导致的错误 */ Target(ElementType.METHOD) Retention(RetentionPolicy.RUNTIME) Documented Inherited publicinterface RequestLock { /** * redis锁前缀 * * return 默认为空但不可为空 */ String prefix() default ; /** * redis锁过期时间 * * return 默认2秒 */ int expire() default 2; /** * redis锁过期时间单位 * * return 默认单位为秒 */ TimeUnit timeUnit() default TimeUnit.SECONDS; /** * redis key分隔符 * * return 分隔符 */ String delimiter() default ; }RequestLock注解定义了几个基础的属性redis锁前缀、redis锁时间、redis锁时间单位、key分隔符。其中前面三个参数比较好理解都是一个锁的基本信息。key分隔符是用来将多个参数合并在一起的比如userName是张三userPhone是123456那么完整的key就是张三123456最后再加上redis锁前缀就组成了一个唯一key。2. 唯一key生成这里有些同学可能就要说了直接拿参数来生成key不就行了吗 额不是不行但我想问一个问题如果这个接口是文章发布的接口你也打算把内容当做key吗要知道Redis的效率跟key的大小息息相关。所以我的建议是选取合适的字段作为key就行了没必要全都加上。要做到参数可选那么用注解的方式最好了注解如下RequestKeyParam.javapackage com.example.requestlock.lock.annotation; import java.lang.annotation.*; /** * description 加上这个注解可以将参数设置为key */ Target({ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD}) Retention(RetentionPolicy.RUNTIME) Documented Inherited public interface RequestKeyParam { }这个注解加到参数上就行没有多余的属性。接下来就是lockKey的生成了代码如下RequestKeyGenerator.javaimport java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.util.ReflectionUtils; import org.springframework.util.StringUtils; publicclass 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 (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(requestLock.delimiter()).append(ReflectionUtils.getField(field, object)); } } } //返回指定前缀的key return requestLock.prefix() sb; } } 由于RequestKeyParam可以放在方法的参数上也可以放在对象的属性上所以这里需要进行两次判断一次是获取方法上的注解一次是获取对象里面属性上的注解。3. 重复提交判断1Redis缓存方式RedisRequestLockAspect.javaimport java.lang.reflect.Method; import com.summo.demo.exception.biz.BizException; import com.summo.demo.model.response.ResponseCodeEnum; 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.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; import org.springframework.data.redis.connection.RedisStringCommands; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.types.Expiration; import org.springframework.util.StringUtils; /** * description 缓存实现 */ Aspect Configuration Order(2) publicclass RedisRequestLockAspect { privatefinal StringRedisTemplate stringRedisTemplate; Autowired public RedisRequestLockAspect(StringRedisTemplate stringRedisTemplate) { this.stringRedisTemplate stringRedisTemplate; } Around(execution(public * * (..)) annotation(com.summo.demo.config.requestlock.RequestLock)) public Object interceptor(ProceedingJoinPoint joinPoint) { MethodSignature methodSignature (MethodSignature)joinPoint.getSignature(); Method method methodSignature.getMethod(); RequestLock requestLock method.getAnnotation(RequestLock.class); if (StringUtils.isEmpty(requestLock.prefix())) { thrownew BizException(ResponseCodeEnum.BIZ_CHECK_FAIL, 重复提交前缀不能为空); } //获取自定义key final String lockKey RequestKeyGenerator.getLockKey(joinPoint); // 使用RedisCallback接口执行set命令设置锁键设置额外选项过期时间和SET_IF_ABSENT选项 final Boolean success stringRedisTemplate.execute( (RedisCallbackBoolean)connection - connection.set(lockKey.getBytes(), newbyte[0], Expiration.from(requestLock.expire(), requestLock.timeUnit()), RedisStringCommands.SetOption.SET_IF_ABSENT)); if (!success) { thrownew BizException(ResponseCodeEnum.BIZ_CHECK_FAIL, 您的操作太快了,请稍后重试); } try { return joinPoint.proceed(); } catch (Throwable throwable) { thrownew BizException(ResponseCodeEnum.BIZ_CHECK_FAIL, 系统异常); } } }这里的核心代码是stringRedisTemplate.execute里面的内容正如注释里面说的“使用RedisCallback接口执行set命令设置锁键设置额外选项过期时间和SET_IF_ABSENT选项”有些同学可能不太清楚SET_IF_ABSENT是个啥,这里我解释一下SET_IF_ABSENT是 RedisStringCommands.SetOption 枚举类中的一个选项用于在执行 SET 命令时设置键值对的时候如果键不存在则进行设置如果键已经存在则不进行设置。2Redisson分布式方式Redisson分布式需要一个额外依赖引入方式dependency groupIdorg.redisson/groupId artifactIdredisson-spring-boot-starter/artifactId version3.10.6/version /dependency由于我之前的代码有一个RedisConfig引入Redisson之后也需要单独配置一下不然会和RedisConfig冲突RedissonConfig.javaimport org.redisson.Redisson; import org.redisson.api.RedissonClient; import org.redisson.config.Config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; Configuration publicclass RedissonConfig { Bean public RedissonClient redissonClient() { Config config new Config(); // 这里假设你使用单节点的Redis服务器 config.useSingleServer() // 使用与Spring Data Redis相同的地址 .setAddress(redis://127.0.0.1:6379); // 如果有密码 //.setPassword(xxxx); // 其他配置参数 //.setDatabase(0) //.setConnectionPoolSize(10) //.setConnectionMinimumIdleSize(2); // 创建RedissonClient实例 return Redisson.create(config); } }配好之后核心代码如下RedissonRequestLockAspect.javaimport java.lang.reflect.Method; import com.summo.demo.exception.biz.BizException; import com.summo.demo.model.response.ResponseCodeEnum; 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; /** * description 分布式锁实现 */ Aspect Configuration Order(2) publicclass RedissonRequestLockAspect { private RedissonClient redissonClient; Autowired public RedissonRequestLockAspect(RedissonClient redissonClient) { this.redissonClient redissonClient; } Around(execution(public * * (..)) annotation(com.summo.demo.config.requestlock.RequestLock)) public Object interceptor(ProceedingJoinPoint joinPoint) { MethodSignature methodSignature (MethodSignature)joinPoint.getSignature(); Method method methodSignature.getMethod(); RequestLock requestLock method.getAnnotation(RequestLock.class); if (StringUtils.isEmpty(requestLock.prefix())) { thrownew BizException(ResponseCodeEnum.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) { thrownew BizException(ResponseCodeEnum.BIZ_CHECK_FAIL, 您的操作太快了,请稍后重试); } //拿到锁后设置过期时间 lock.lock(requestLock.expire(), requestLock.timeUnit()); try { return joinPoint.proceed(); } catch (Throwable throwable) { thrownew BizException(ResponseCodeEnum.BIZ_CHECK_FAIL, 系统异常); } } catch (Exception e) { thrownew BizException(ResponseCodeEnum.BIZ_CHECK_FAIL, 您的操作太快了,请稍后重试); } finally { //释放锁 if (isLocked lock.isHeldByCurrentThread()) { lock.unlock(); } } } }Redisson的核心思路就是抢锁当一次请求抢到锁之后对锁加一个过期时间在这个时间段内重复的请求是无法获得这个锁也不难理解。4. 测试一下第一次提交添加用户成功短时间内重复提交BIZ-0001:您的操作太快了,请稍后重试过几秒后再次提交添加用户成功从测试的结果上看防抖是做到了但是随着缓存消失、锁失效还是可以发起同样的请求所以要真正做到接口幂等性还需要业务代码的判断、设置数据库表的UK索引等操作。 我在文章里面说到生成唯一key的时候没有加用户相关的信息比如用户ID、IP属地等真实生产环境建议加上这些可以更好地减少误判。