SpringBoot接口+Redis解决用户重复提交问题
创始人
2024-06-02 19:17:31
0次

前言

1. 为什么会出现用户重复提交

  • 网络延迟的情况下用户多次点击submit按钮导致表单重复提交;
  • 用户提交表单后,点击【刷新】按钮导致表单重复提交(点击浏览器的刷新按钮,就是把浏览器上次做的事情再做一次,因为这样也会导致表单重复提交);
  • 用户提交表单后,点击浏览器的【后退】按钮回退到表单页面后进行再次提交。

2. 重复提交不拦截可能导致的问题

  • 重复数据入库,造成脏数据。即使数据库表有UK索引,该操作也会增加系统的不必要负担;
  • 会成为黑客爆破攻击的入口,大量的请求会导致应用崩溃;
  • 用户体验差,多条重复的数据还需要一条条的删除等。

3. 解决办法

办法有很多,我这里只说一种,利用Redis的set方法搞定(不是redisson)

项目代码

项目结构

在这里插入图片描述

配置文件

pom.xml


4.0.0org.springframework.bootspring-boot-starter-parent2.7.9 com.exampleRequestLock0.0.1-SNAPSHOTRequestLockDemo project for Spring Boot1.8org.springframework.bootspring-boot-starter-data-redisorg.springframework.bootspring-boot-starter-weborg.aspectjaspectjweaver1.9.5org.springframework.bootspring-boot-maven-plugin

application.properties

spring.application.name=RequestLock
server.port=8080# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=20
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=10
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=1000

代码文件

RequestLockApplication.java

package com.example.requestlock;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class RequestLockApplication {public static void main(String[] args) {SpringApplication.run(RequestLockApplication.class, args);}}

User.java

package com.example.requestlock.model;import com.example.requestlock.lock.annotation.RequestKeyParam;public class User {private String name;private Integer age;@RequestKeyParam(name = "phone")private String phone;public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public String getPhone() {return phone;}public void setPhone(String phone) {this.phone = phone;}@Overridepublic String toString() {return "User{" +"name='" + name + '\'' +", age=" + age +", phone='" + phone + '\'' +'}';}
}

RequestKeyParam.java

package com.example.requestlock.lock.annotation;import java.lang.annotation.*;/*** @description 加上这个注解可以将参数也设置为key,唯一key来源*/
@Target({ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface RequestKeyParam {/*** key值名称** @return 默认为空*/String name() default "";
}

RequestLock.java

package com.example.requestlock.lock.annotation;import java.lang.annotation.*;
import java.util.concurrent.TimeUnit;/*** @description 请求防抖锁,用于防止前端重复提交导致的错误*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface 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 ":";
}

RequestLockMethodAspect.java

package com.example.requestlock.lock.aspect;import com.example.requestlock.lock.annotation.RequestLock;
import com.example.requestlock.lock.keygenerator.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.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
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;import java.lang.reflect.Method;/*** @description 请求锁切面处理器*/
@Aspect
@Configuration
public class RequestLockMethodAspect {private final StringRedisTemplate stringRedisTemplate;private final RequestKeyGenerator requestKeyGenerator;@Autowiredpublic RequestLockMethodAspect(StringRedisTemplate stringRedisTemplate, RequestKeyGenerator requestKeyGenerator) {this.requestKeyGenerator = requestKeyGenerator;this.stringRedisTemplate = stringRedisTemplate;}@Around("execution(public * * (..)) && @annotation(com.example.requestlock.lock.annotation.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 RuntimeException("重复提交前缀不能为空");return "重复提交前缀不能为空";}//获取自定义keyfinal String lockKey = requestKeyGenerator.getLockKey(joinPoint);final Boolean success = stringRedisTemplate.execute((RedisCallback) connection -> connection.set(lockKey.getBytes(), new byte[0], Expiration.from(requestLock.expire(), requestLock.timeUnit()), RedisStringCommands.SetOption.SET_IF_ABSENT));if (!success) {
//            throw new RuntimeException("您的操作太快了,请稍后重试");return "您的操作太快了,请稍后重试";}try {return joinPoint.proceed();} catch (Throwable throwable) {
//            throw new RuntimeException("系统异常");return "系统异常";}}
}

RequestKeyGenerator.java

package com.example.requestlock.lock.keygenerator;import org.aspectj.lang.ProceedingJoinPoint;/*** 加锁key生成器*/
public interface RequestKeyGenerator {/*** 获取AOP参数,生成指定缓存Key** @param joinPoint 切入点* @return 返回key值*/String getLockKey(ProceedingJoinPoint joinPoint);
}

RequestKeyGeneratorImpl.java

package com.example.requestlock.lock.keygenerator.impl;import com.example.requestlock.lock.annotation.RequestKeyParam;
import com.example.requestlock.lock.annotation.RequestLock;
import com.example.requestlock.lock.keygenerator.RequestKeyGenerator;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Service;
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;@Service
public class RequestKeyGeneratorImpl implements RequestKeyGenerator {@Overridepublic 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 cacheParams = parameters[i].getAnnotation(RequestKeyParam.class);//如果属性不是CacheParam注解,则不处理if (cacheParams == null) {continue;}//如果属性是CacheParam注解,则拼接 连接符(:)+ CacheParamsb.append(requestLock.delimiter()).append(args[i]);}//如果方法上没有加CacheParam注解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) {//判断字段上是否有CacheParam注解final RequestKeyParam annotation = field.getAnnotation(RequestKeyParam.class);//如果没有,跳过if (annotation == null) {continue;}//如果有,设置Accessible为true(为true时可以使用反射访问私有变量,否则不能访问私有变量)field.setAccessible(true);//如果属性是CacheParam注解,则拼接 连接符(:)+ CacheParamsb.append(requestLock.delimiter()).append(ReflectionUtils.getField(field, object));}}}//返回指定前缀的keyreturn requestLock.prefix() + sb;}
}

UserController.java

package com.example.requestlock.controller;import com.example.requestlock.lock.annotation.RequestLock;
import com.example.requestlock.model.User;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/user")
public class UserController {@PostMapping("/addUser1")public String addUser1(@RequestBody User user) {System.out.println("不做任何处理" + user);return "添加成功";}@PostMapping("/addUser2")@RequestLock(prefix = "addUser")public String addUser2(@RequestBody User user) {System.out.println("防重提交" + user);return "添加成功";}
}

效果展示

调用addUser1接口

在这里插入图片描述
这里无论点击多少次提交,都会展示添加“添加成功”,这样是不行的。

调用addUser2接口

在这里插入图片描述
第一次提交,“添加成功”。
在这里插入图片描述
快速点击第二次提交,就会出现“您的操作太快了,请稍后重试”提示。

原理解释

该RequestLock(请求锁)利用了Redis的单线程处理以及Key值过期特点,核心通过RequestLock、RequestKeyParam注解生成一个唯一的key值,存入redis后设置一个过期时间(1-3秒),当第二次请求的时候,判断生成的key值是否在Redis中存在,如果存在则认为第二次提交是重复的。

相关内容

热门资讯

马斯克“脑机”获批意味着什么 ... Neuralink在12月1日公开的制造影像展示了德州奥斯汀附近洁净车间正在生产的一种约硬币大小的植...
俄敦促各国撤离驻乌外交人员 基... 乌克兰当局报告称,周三俄罗斯无人机袭击了基辅,导致至少9人死亡、59人受伤。德国大使馆和国家歌剧院在...
中国汽车行业第二轮淘汰赛已打响... 无法持续创造价值的企业将被淘汰。一款车卖得好,曾经足以改变一家汽车公司的命运。坦克300就是一个典型...
种粮大户:种地不相信科技不行 ... 12月3日,国务院新闻办公室举行“新征程上的奋斗者”中外记者见面会,邀请农业农村领域代表围绕“科技兴...
俄方回应网传英法领导人聊天记录... 俄罗斯总统新闻秘书佩斯科夫批评称,有通话记录显示法国总统马克龙和英国首相伯纳姆意图延长乌克兰冲突,并...
戴军将出席2026星光大赏 星... 今年12月,腾讯视频将星光大赏扩展为一场长达16天的“星光周”。活动从12月5日杭州开始,至12月2...
鼻子短期变高是因为夹“肿”了 ... 近期,一些声称能够“无创挺鼻、缩小鼻翼、重塑鼻形”的美鼻夹在网络上热销。医生指出,物理外力并不能改变...
那威生前最后一次露面 泡馍宴学... 2026年12月3日的冬夜,寒意在北京城蔓延。社交平台上突然传来“那威去世”的消息,令许多观众感到震...
主持人那威去世 一路走好 12月3日,博主@肉凯儿发文悼念:“@那威老师一路走好”。那威是中国著名主持人、演员及五子棋棋手,1...
两车碰撞致人死无接触第三方赔2... 车祸撞死人达成谅解书的赔偿金额没有固定标准,通常在20万到50万元之间。这取决于事故责任划分、死者家...
西部第一大省再迎新机场 34年... 周末下班,直奔乐山。这句火遍全网的文旅口号,在12月有了新的意义。12月16日,乐山机场将正式通航,...
朱丹说没钱不能娶李嘉格 经济基... #朱丹说李嘉格男友没钱不行#朱丹真的好敢说!聊李嘉格这段直接点破现实,勤快和真心固然重要,但没钱不行...
汽车公司排队找宁德时代一起做换... 不到一周,宁德时代的换电合作名单新增了四个汽车品牌。11月26日,东风汽车与华为联合打造的奕境宣布接...
比特币暴跌背后原因 地缘政治与... 当你以为比特币是避险资产时,现实总能给出响亮的耳光。12月3日,加密货币市场全线重挫,比特币24小时...
河南桐柏猪瘟致大量生猪死亡?假... 近日,有网民在网络平台发布了一段标题为《桐柏县出现猪瘟》的视频,声称“桐柏县出现猪瘟,造成大量生猪异...
老人猥亵8岁女童辩称是长辈式关... 2025年12月6日,岳阳市岳阳楼区天虹商场内发生一起猥亵儿童案。8岁女童晞晞在该商场某电玩城玩耍时...
加密货币全网爆仓 市场调整加深 加密货币市场的调整仍在继续。12月3日,据CoinGlass统计,过去24小时内,比特币跌破5.7万...
密码学的死讯被夸大了吗 AI加... 2026年11月30日,A股网络安全板块开盘异动。三未信安涨停,格尔软件封板,绿盟科技、电科网安、安...
北京457家医院影像互通 减少... 12月1日,北京市市场监管局发布消息,市卫生健康委、市市场监管局联合组织市医学影像质量控制和改进中心...
雅思老师独自赴泰国旅行失联 家... 11月30日晚,33岁的上海英语机构雅思培训老师刘英俊在泰国曼谷沙吞区彻底失联。他失联前的种种细节让...