2025年重复提交问题解决方案

重复提交问题解决方案今天来讲讲最常见的重复提交问题 导致重复提交的问题有很多种 比如 快速点击了两次提交按钮 浏览器使用后退功能导致重复提交表单 nginx 重发等情况导致 解决的办法有很多种 比如前端就有利用 JS 在第一次提交之后 禁用提交按钮或者设置一个特殊的字段标志是否第一次提交 后端实现也有很多种方法

大家好,我是讯享网,很高兴认识大家。

今天来讲讲最常见的重复提交问题,导致重复提交的问题有很多种,比如:快速点击了两次提交按钮、浏览器使用后退功能导致重复提交表单、nginx重发等情况导致。解决的办法有很多种,比如前端就有利用JS在第一次提交之后,禁用提交按钮或者设置一个特殊的字段标志是否第一次提交。后端实现也有很多种方法,我自己使用过的2种,今天就介绍一下。

一、利用本地锁,spring AOP切面拦截,对在规定时间内提交的数据进行校验,如果完全一致,则认为是重复提交,丢弃处理。

1、实现一个用于防止重复提交的注解,@Resubmit

import java.lang.annotation.*; @Target({METHOD}) // 规定此注解只能用于方法上 @Retention(RUNTIME) @Documented public @interface Resubmit { / * 延时时间 在延时多久后可以再次提交 * * @return Time unit is one second */ int delaySeconds() default 5; }

讯享网

2、实例化本地锁,锁的相关处理类

讯享网import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.springframework.util.DigestUtils; / * @author LBJ * 重复提交锁 */ public final class ResubmitLock { private static final ConcurrentHashMap<String, Object> LOCK_CACHE = new ConcurrentHashMap<>(128); private static final ScheduledThreadPoolExecutor EXECUTOR = new ScheduledThreadPoolExecutor(5, new ThreadPoolExecutor.DiscardPolicy()); private ResubmitLock() {} / * 静态内部类 单例模式 * * @return */ private static class SingletonInstance { private static final ResubmitLock INSTANCE = new ResubmitLock(); } public static ResubmitLock getInstance() { return SingletonInstance.INSTANCE; } public static String handleKey(String param) { return DigestUtils.md5DigestAsHex( param == null ? "".getBytes() : param.getBytes()); } / * 加锁 putIfAbsent 是原子操作保证线程安全 * * @param key 对应的key * @param value * @return */ public boolean lock(final String key, Object value) { return Objects.isNull(LOCK_CACHE.putIfAbsent(key, value)); } / * 延时释放锁 用以控制短时间内的重复提交 * * @param lock 是否需要解锁 * @param key 对应的key * @param delaySeconds 延时时间 */ public void unLock(final boolean lock, final String key, final int delaySeconds) { if (lock) { EXECUTOR.schedule(() -> { LOCK_CACHE.remove(key); }, delaySeconds, TimeUnit.SECONDS); } } }

3、AOP切面拦截提交的参数

import lombok.extern.log4j.Log4j; 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.stereotype.Component; import com.alibaba.fastjson.JSONObject; import com.xxx.xxx.xxx.annotation.Resubmit; import java.lang.reflect.Method; / * @ClassName RequestDataAspect * @Description 数据重复提交校验 * @Author LBJ * @Date 2019/12/23 / @Log4j @Aspect @Component public class ResubmitDataAspect { private final static Object PRESENT = new Object(); @Around("@annotation(com.xxx.xxx.xxx.annotation.Resubmit)") public Object handleResubmit(ProceedingJoinPoint joinPoint) throws Throwable { Method method = ((MethodSignature) joinPoint.getSignature()).getMethod(); //获取注解信息 Resubmit annotation = method.getAnnotation(Resubmit.class); int delaySeconds = annotation.delaySeconds(); String key = ""; Object[] args = joinPoint.getArgs(); //获取参数 for (Object arg : args) { if (arg instanceof SubmitInVo) { // SubmitInVo是自定义入参的VO //解析参数 SubmitInVo in = (SubmitInVo) arg; if (in != null) { String jsonStr = JSONObject.toJSONString(in); JSONObject data = JSONObject.parseObject(jsonStr); SortMap<String, String> paramsMap = new TreeMap<String, String>(); data.forEach((k, v) -> { paramsMap.put(k, v); }); StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String> entry : paramsMap.entrySet()) { sb.append(entry.getKey()).append(entry.getValue()); } //生成加密参数 使用了content_MD5的加密方式 key = ResubmitLock.handleKey(sb.toString()); } } } //执行锁 boolean lock = false; try { //设置解锁key lock = ResubmitLock.getInstance().lock(key, PRESENT); if (lock) { //放行 return joinPoint.proceed(); } else { //响应重复提交异常 JSONObject resp = new JSONObject(); resp.put("failure", "请勿重复提交"); return resp; } } finally { //设置解锁key和解锁时间 ResubmitLock.getInstance().unLock(lock, key, delaySeconds); } } }

4、使用示例

讯享网 @PostMapping("/save") @Resubmit(delaySeconds = 10) public JSONObject save(@RequestBody @Validated SubmitInVo in) { return ""; }

 

二、第二种借助分布式redis锁(参考其他文章,地址:https://blog.battcn.com/2018/06/13/springboot/v2-cache-redislock/)


讯享网

在 pom.xml 中添加上 starter-web、starter-aop、starter-data-redis 的依赖即可

<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> </dependencies>

属性配置 在 application.properites 资源文件中添加 redis 相关的配置项

讯享网spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.password=redis

主要实现方式:

熟悉 Redis 的朋友都知道它是线程安全的,我们利用它的特性可以很轻松的实现一个分布式锁,如 opsForValue().setIfAbsent(key,value)它的作用就是如果缓存中没有当前 Key 则进行缓存同时返回 true 反之亦然;

当缓存后给 key 在设置个过期时间,防止因为系统崩溃而导致锁迟迟不释放形成死锁;那么我们是不是可以这样认为当返回 true 我们认为它获取到锁了,在锁未释放的时候我们进行异常的抛出…

package com.battcn.interceptor; import com.battcn.annotation.CacheLock; import com.battcn.utils.RedisLockHelper; 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.util.StringUtils; import java.lang.reflect.Method; import java.util.UUID; / * redis 方案 * * @author Levin * @since 2018/6/12 0012 */ @Aspect @Configuration public class LockMethodInterceptor { @Autowired public LockMethodInterceptor(RedisLockHelper redisLockHelper, CacheKeyGenerator cacheKeyGenerator) { this.redisLockHelper = redisLockHelper; this.cacheKeyGenerator = cacheKeyGenerator; } private final RedisLockHelper redisLockHelper; private final CacheKeyGenerator cacheKeyGenerator; @Around("execution(public * *(..)) && @annotation(com.battcn.annotation.CacheLock)") public Object interceptor(ProceedingJoinPoint pjp) { MethodSignature signature = (MethodSignature) pjp.getSignature(); Method method = signature.getMethod(); CacheLock lock = method.getAnnotation(CacheLock.class); if (StringUtils.isEmpty(lock.prefix())) { throw new RuntimeException("lock key don't null..."); } final String lockKey = cacheKeyGenerator.getLockKey(pjp); String value = UUID.randomUUID().toString(); try { // 假设上锁成功,但是设置过期时间失效,以后拿到的都是 false final boolean success = redisLockHelper.lock(lockKey, value, lock.expire(), lock.timeUnit()); if (!success) { throw new RuntimeException("重复提交"); } try { return pjp.proceed(); } catch (Throwable throwable) { throw new RuntimeException("系统异常"); } } finally { // TODO 如果演示的话需要注释该代码;实际应该放开 redisLockHelper.unlock(lockKey, value); } } }

RedisLockHelper 通过封装成 API 方式调用,灵活度更加高

讯享网package com.battcn.utils; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration; 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.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; / * 需要定义成 Bean * * @author Levin * @since 2018/6/15 0015 */ @Configuration @AutoConfigureAfter(RedisAutoConfiguration.class) public class RedisLockHelper { private static final String DELIMITER = "|"; / * 如果要求比较高可以通过注入的方式分配 */ private static final ScheduledExecutorService EXECUTOR_SERVICE = Executors.newScheduledThreadPool(10); private final StringRedisTemplate stringRedisTemplate; public RedisLockHelper(StringRedisTemplate stringRedisTemplate) { this.stringRedisTemplate = stringRedisTemplate; } / * 获取锁(存在死锁风险) * * @param lockKey lockKey * @param value value * @param time 超时时间 * @param unit 过期单位 * @return true or false */ public boolean tryLock(final String lockKey, final String value, final long time, final TimeUnit unit) { return stringRedisTemplate.execute((RedisCallback<Boolean>) connection -> connection.set(lockKey.getBytes(), value.getBytes(), Expiration.from(time, unit), RedisStringCommands.SetOption.SET_IF_ABSENT)); } / * 获取锁 * * @param lockKey lockKey * @param uuid UUID * @param timeout 超时时间 * @param unit 过期单位 * @return true or false */ public boolean lock(String lockKey, final String uuid, long timeout, final TimeUnit unit) { final long milliseconds = Expiration.from(timeout, unit).getExpirationTimeInMilliseconds(); boolean success = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, (System.currentTimeMillis() + milliseconds) + DELIMITER + uuid); if (success) { stringRedisTemplate.expire(lockKey, timeout, TimeUnit.SECONDS); } else { String oldVal = stringRedisTemplate.opsForValue().getAndSet(lockKey, (System.currentTimeMillis() + milliseconds) + DELIMITER + uuid); final String[] oldValues = oldVal.split(Pattern.quote(DELIMITER)); if (Long.parseLong(oldValues[0]) + 1 <= System.currentTimeMillis()) { return true; } } return success; } / * @see <a href="http://redis.io/commands/set">Redis Documentation: SET</a> */ public void unlock(String lockKey, String value) { unlock(lockKey, value, 0, TimeUnit.MILLISECONDS); } / * 延迟unlock * * @param lockKey key * @param uuid client(最好是唯一键的) * @param delayTime 延迟时间 * @param unit 时间单位 */ public void unlock(final String lockKey, final String uuid, long delayTime, TimeUnit unit) { if (StringUtils.isEmpty(lockKey)) { return; } if (delayTime <= 0) { doUnlock(lockKey, uuid); } else { EXECUTOR_SERVICE.schedule(() -> doUnlock(lockKey, uuid), delayTime, unit); } } / * @param lockKey key * @param uuid client(最好是唯一键的) */ private void doUnlock(final String lockKey, final String uuid) { String val = stringRedisTemplate.opsForValue().get(lockKey); final String[] values = val.split(Pattern.quote(DELIMITER)); if (values.length <= 0) { return; } if (uuid.equals(values[1])) { stringRedisTemplate.delete(lockKey); } } }

 

小讯
上一篇 2025-03-24 17:24
下一篇 2025-02-09 14:57

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/22748.html