当前位置: 首页 > web >正文

分布式部署下如何做接口防抖---使用分布式锁

        防抖也即防重复提交,那么如何确定两次接口就是重复的呢?首先,我们需要给这两次接口的调用加一个时间间隔,大于这个时间间隔的一定不是重复提交;其次,两次请求提交的参数比对,不一定要全部参数,选择标识性强的参数即可(生产环境还可以加上用户ID);最后,如果想做的更好一点,还可以加一个请求地址的对比。

        分布式部署下接口防抖有有很多方法,如:使用共享缓存,使用分布式锁,在web开发中一般新增后者

        思路如下:

1. 自定义注解@RequestLock,用于标记需要防抖的接口方法,记录锁的一些信息如:锁过期时间、时间单位等。

2. 自定义@RequestKeyParam注解用于指定生成唯一键的参数(生成锁名的依据)。

3. 封装RequestKeyGenerator 类定义锁的生成逻辑,返回生成的锁名。

4. 实现一个切入点为添加了@RequestLock注解的方法的环绕通知,通知的内容是:生成锁名key, 获取目标对象的的@RequestLock携带的锁过期作为锁名key存入Redis的TTL。

5. 在需要增强的方法上添加@RequestLock,用于加锁的参数上添加@RequestKeyParam。

实现过程:

@RequestLock

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RequestLock {String prefix() default "";long expire() default 5; // 锁过期时间,单位:秒String timeUnit() default "SECONDS";String delimiter() default "&";
}

@RequestKeyParam

import java.lang.annotation.ElementType;
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 {}

RequestKeyGenerator 类( 由于 @RequestKeyParam 可以放在方法的参数上,也可以放在对象的属性上,所以这里需要进行两次判断,一次是获取方法上的注解,一次是获取对象里面属性上的注解。)

import 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;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 (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));}}}//返回指定前缀的keyreturn requestLock.prefix() + sb;}
}

Redis

import 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)
public class RedisRequestLockAspect {private final StringRedisTemplate stringRedisTemplate;@Autowiredpublic 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())) {throw new BizException(ResponseCodeEnum.BIZ_CHECK_FAIL, "重复提交前缀不能为空");}//获取自定义keyfinal String lockKey = RequestKeyGenerator.getLockKey(joinPoint);// 使用RedisCallback接口执行set命令,设置锁键;设置额外选项:过期时间和SET_IF_ABSENT选项final Boolean success = stringRedisTemplate.execute((RedisCallback<Boolean>)connection -> connection.set(lockKey.getBytes(), new byte[0],Expiration.from(requestLock.expire(), requestLock.timeUnit()),RedisStringCommands.SetOption.SET_IF_ABSENT));if (!success) {throw new BizException(ResponseCodeEnum.BIZ_CHECK_FAIL, "您的操作太快了,请稍后重试");}try {return joinPoint.proceed();} catch (Throwable throwable) {throw new BizException(ResponseCodeEnum.BIZ_CHECK_FAIL, "系统异常");}}
}

 接口方法和实体类

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;@RestController
public class UserController {@PostMapping("/add")@RequestLock(prefix = "user_add_")public ResponseEntity<String> addUser(@RequestBody AddUserRequest addUserRequest) {// 这里假设调用服务层方法添加用户,实际需注入 userService 并确保其有 add 方法// 示例中先注释掉,实际使用要补充服务层调用逻辑// userService.add(addUserRequest);return ResponseEntity.ok("添加用户成功");}
}import lombok.Data;@Data
public class AddUserRequest {@RequestKeyParamprivate String userName;@RequestKeyParamprivate String userPhone;// 其他字段...
}


http://www.xdnf.cn/news/14892.html

相关文章:

  • 站在 Java 程序员的角度如何学习和使用 AI?从 MVC 到智能体,范式变了!
  • 清除浮动/避开margin折叠:前端CSS中BFC的特点与限制
  • springMvc的简单使用:要求在浏览器发起请求,由springMVC接受请求并响应,将个人简历信息展示到浏览器
  • pdf 合并 python实现(已解决)
  • springboot切面编程
  • 【Java面试】RocketMQ的设计原理
  • 【数字后端】- tcbn28hpcplusbwp30p140,标准单元库命名含义
  • 按月设置索引名的完整指南:Elasticsearch日期索引实践
  • 嵌入式软件面经(四)Q:请说明在 ILP32、LP64 与 LLP64 三种数据模型下,常见基本类型及指针的 sizeof 值差异,并简要解释其原因
  • 提示技术系列——程序辅助语言模型
  • HCIA-实现VLAN间通信
  • 智能物流革命:Spring Boot+AI实现最优配送路径规划
  • 红黑树:高效平衡的秘密
  • Spring生态在Java开发
  • Android Native 之 init初始化selinux机制
  • 【Note】《深入理解Linux内核》 Chapter 5 :内存地址的表示——Linux虚拟内存体系结构详解
  • 【RHCSA-Linux考试题目笔记(自用)】servera的题目
  • mac Maven配置报错The JAVA_HOME environment variable is not defined correctly的解决方法
  • 「ECG信号处理——(20)基于心电和呼吸的因果分析模型」2025年7月2日
  • 【Python】Python / PyCharm 虚拟环境详搭建与使用详解
  • U+平台配置免密登录、安装Hadoop配置集群、Spark配置
  • FIRST携手Fortinet推出全新CORE计划,致力于提升全球网络能力
  • jQuery EasyUI 安装使用教程
  • [Python 基础课程]数字
  • 【学习笔记】Python中主函数调用的方式
  • AngularJS 安装使用教程
  • kubernetes pod调度基础
  • Ubuntu系统开发板借助windows中转上网
  • 类加载生命周期与内存区域详解
  • [特殊字符] 分享裂变新姿势:用 UniApp + Vue3 玩转小程序页面分享跳转!