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中存在,如果存在则认为第二次提交是重复的。

相关内容

热门资讯

122.(leaflet篇)l... 听老人家说:多看美女会长寿 地图之家总目录(订阅之前建议先查看该博客) 文章末尾处提供保证可运行...
育碧GDC2018程序化大世界... 1.传统手动绘制森林的问题 采用手动绘制的方法的话,每次迭代地形都要手动再绘制森林。这...
育碧GDC2018程序化大世界... 1.传统手动绘制森林的问题 采用手动绘制的方法的话,每次迭代地形都要手动再绘制森林。这...
Vue使用pdf-lib为文件... 之前也写过两篇预览pdf的,但是没有加水印,这是链接:Vu...
PyQt5数据库开发1 4.1... 文章目录 前言 步骤/方法 1 使用windows身份登录 2 启用混合登录模式 3 允许远程连接服...
Android studio ... 解决 Android studio 出现“The emulator process for AVD ...
Linux基础命令大全(上) ♥️作者:小刘在C站 ♥️个人主页:小刘主页 ♥️每天分享云计算网络运维...
再谈解决“因为文件包含病毒或潜... 前面出了一篇博文专门来解决“因为文件包含病毒或潜在的垃圾软件”的问题,其中第二种方法有...
南京邮电大学通达学院2023c... 题目展示 一.问题描述 实验题目1 定义一个学生类,其中包括如下内容: (1)私有数据成员 ①年龄 ...
PageObject 六大原则 PageObject六大原则: 1.封装服务的方法 2.不要暴露页面的细节 3.通过r...
【Linux网络编程】01:S... Socket多进程 OVERVIEWSocket多进程1.Server2.Client3.bug&...
数据结构刷题(二十五):122... 1.122. 买卖股票的最佳时机 II思路:贪心。把利润分解为每天为单位的维度,然后收...
浏览器事件循环 事件循环 浏览器的进程模型 何为进程? 程序运行需要有它自己专属的内存空间࿰...
8个免费图片/照片压缩工具帮您... 继续查看一些最好的图像压缩工具,以提升用户体验和存储空间以及网站使用支持。 无数图像压...
计算机二级Python备考(2... 目录  一、选择题 1.在Python语言中: 2.知识点 二、基本操作题 1. j...
端电压 相电压 线电压 记得刚接触矢量控制的时候,拿到板子,就赶紧去测各种波形,结...
如何使用Python检测和识别... 车牌检测与识别技术用途广泛,可以用于道路系统、无票停车场、车辆门禁等。这项技术结合了计...
带环链表详解 目录 一、什么是环形链表 二、判断是否为环形链表 2.1 具体题目 2.2 具体思路 2.3 思路的...
【C语言进阶:刨根究底字符串函... 本节重点内容: 深入理解strcpy函数的使用学会strcpy函数的模拟实现⚡strc...
Django web开发(一)... 文章目录前端开发1.快速开发网站2.标签2.1 编码2.2 title2.3 标题2.4 div和s...