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

相关内容

热门资讯

switch lite刷安卓系... 你有没有想过,你的Switch Lite除了玩那些可爱的任天堂游戏,还能干些什么呢?没错,今天我要给...
想买华为但是安卓系统,尽享安卓... 最近是不是也被华为的新款手机给迷住了?看着那流畅的线条和强大的性能,是不是心动了呢?但是,一想到安卓...
怎么拷安卓系统文件,安卓系统文... 你有没有想过,手机里的那些安卓系统文件,其实就像是一扇通往手机世界的秘密通道呢?想要深入了解你的安卓...
安卓系统移植按键失灵,安卓系统... 最近你的安卓手机是不是也遇到了按键失灵的尴尬情况呢?这可真是让人头疼啊!别急,今天就来给你详细解析一...
安卓系统更新管理在哪,全面解析... 你有没有发现,你的安卓手机最近是不是总在提醒你更新系统呢?别急,别急,今天就来手把手教你,安卓系统更...
安卓系统哪里出的,从诞生地到全... 你有没有想过,我们每天离不开的安卓系统,它究竟是从哪里冒出来的呢?是不是觉得这个问题有点儿像是在问星...
最好的电脑安卓系统,最佳电脑安... 亲爱的电脑迷们,你是否在寻找一款既能满足你工作需求,又能让你畅享娱乐的电脑操作系统呢?今天,我要给你...
安卓系统保密性,守护隐私的坚实... 你知道吗?在这个信息爆炸的时代,保护个人隐私变得比以往任何时候都重要。尤其是对于安卓系统用户来说,了...
苹果系统下载安卓版本,安卓版本... 你有没有想过,为什么苹果系统的手机那么受欢迎,却还有人想要下载安卓版本呢?这背后可是有着不少故事呢!...
安卓系统如何下载carplay... 你是不是也和我一样,对安卓系统上的CarPlay功能充满了好奇?想象在安卓手机上就能享受到苹果Car...
退回安卓系统的理由,揭秘安卓系... 你有没有想过,为什么有些人会选择退回到安卓系统呢?这可不是一件简单的事情,背后可是有着不少原因哦!让...
安卓机系统互通吗,共创智能生态 你有没有想过,你的安卓手机里的应用和电脑上的安卓应用是不是可以无缝对接呢?是不是有时候觉得手机上的某...
安卓源码 添加系统应用,系统应... 你有没有想过,手机里的那些系统应用是怎么来的?是不是觉得它们就像天外来物,神秘又神奇?其实,只要你愿...
安卓系统能否播放flv,全面解... 你有没有想过,你的安卓手机里那些珍贵的FLV视频文件,到底能不能顺利播放呢?这可是个让人挠头的问题,...
奔驰c系安卓系统,智能驾驶体验... 你有没有发现,最近开奔驰C系的小伙伴们都在悄悄地谈论一个新玩意儿——安卓系统!没错,就是那个我们手机...
安卓系统打印服务名称,探寻打印... 你有没有发现,手机里的安卓系统里有一个神奇的小功能,那就是打印服务!没错,就是那个可以让你把手机里的...
安卓系统主界面切换,探索个性化... 你有没有发现,每次打开安卓手机,那主界面切换的瞬间,就像是打开了一扇通往新世界的大门呢?今天,就让我...
安卓系统xml是什么,Andr... 你有没有想过,你的手机里那些看起来平平无奇的图标和布局,其实背后有着一套复杂的“语言”在支撑呢?没错...
魔盒正版安卓系统下载,畅享极致... 亲爱的读者们,你是否曾梦想拥有一款纯净无瑕的安卓系统,就像打开了一个神秘的魔盒,里面蕴藏着无尽的惊喜...
苹果安卓系统销量,系统销量争霸... 你有没有发现,最近手机圈里有个大热门话题,那就是苹果和安卓系统的销量大战!没错,就是那个让无数手机爱...