1. 首页
  2. IT资讯

8 种方案,帮你解决重复提交问题

“u003Cimg src=”http:u002Fu002Fp1.pstatp.comu002Flargeu002Fpgc-imageu002FRf8n3jdBqecfy8″ img_width=”1080″ img_height=”345″ alt=”8 种方案,帮你解决重复提交问题” inline=”0″u003Eu003Cpu003E作者:锦成同学u003Cu002Fpu003Eu003Cpu003E来源:juejin.imu002Fpostu002F5d31928c51882564c966a71cu003Cu002Fpu003Eu003Cpu003Eu003Cu002Fpu003Eu003Ch1 toutiao-origin=”h3″u003E1.什么是幂等u003Cu002Fh1u003Eu003Cimg src=”http:u002Fu002Fp1.pstatp.comu002Flargeu002Fpgc-imageu002FRg5SkPM1i2PD0S” img_width=”421″ img_height=”32″ alt=”8 种方案,帮你解决重复提交问题” inline=”0″u003Eu003Cpu003E在我们编程中常见幂等u003Cu002Fpu003Eu003Culu003Eu003Cliu003Eu003Cpu003Eselect查询天然幂等u003Cu002Fpu003Eu003Cu002Fliu003Eu003Cliu003Eu003Cpu003Edelete删除也是幂等,删除同一个多次效果一样u003Cu002Fpu003Eu003Cu002Fliu003Eu003Cliu003Eu003Cpu003Eupdate直接更新某个值的,幂等u003Cu002Fpu003Eu003Cu002Fliu003Eu003Cliu003Eu003Cpu003Eupdate更新u003Ci class=”chrome-extension-mutihighlight chrome-extension-mutihighlight-style-2″u003E累加u003Cu002Fiu003E操作的,非幂等u003Cu002Fpu003Eu003Cu002Fliu003Eu003Cliu003Eu003Cpu003Einsert非幂等操作,每次新增一条u003Cu002Fpu003Eu003Cu002Fliu003Eu003Cu002Fulu003Eu003Cpu003Eu003Cu002Fpu003Eu003Ch1 toutiao-origin=”h3″u003E2.产生原因u003Cu002Fh1u003Eu003Cpu003E由于重复点击或者网络重发 eg:u003Cu002Fpu003Eu003Culu003Eu003Cliu003Eu003Cpu003E点击提交按钮两次;u003Cu002Fpu003Eu003Cu002Fliu003Eu003Cliu003Eu003Cpu003E点击刷新按钮;u003Cu002Fpu003Eu003Cu002Fliu003Eu003Cliu003Eu003Cpu003E使用浏览器后退按钮重复之前的操作,导致重复提交表单;u003Cu002Fpu003Eu003Cu002Fliu003Eu003Cliu003Eu003Cpu003E使用浏览器历史记录重复提交表单;u003Cu002Fpu003Eu003Cu002Fliu003Eu003Cliu003Eu003Cpu003E浏览器重复的u003Ci class=”chrome-extension-mutihighlight chrome-extension-mutihighlight-style-3″u003EHTTPu003Cu002Fiu003E请;u003Cu002Fpu003Eu003Cu002Fliu003Eu003Cliu003Eu003Cpu003Enginx重发等情况;u003Cu002Fpu003Eu003Cu002Fliu003Eu003Cliu003Eu003Cpu003E分布式RPC的try重发等;u003Cu002Fpu003Eu003Cu002Fliu003Eu003Cu002Fulu003Eu003Cpu003Eu003Cu002Fpu003Eu003Ch1 toutiao-origin=”h3″u003E3.解决方案u003Cu002Fh1u003Eu003Cpu003Eu003Cstrong toutiao-origin=”strong” class=”highlight-text”u003E1、前端js提交禁止按钮可以用一些js组件u003Cu002Fstrongu003Eu003Cu002Fpu003Eu003Cpu003Eu003Cstrong toutiao-origin=”strong” class=”highlight-text”u003E2、使用Postu002FRedirectu002FGet模式u003Cu002Fstrongu003Eu003Cu002Fpu003Eu003Cpu003E在提交后执行页面重定向,这就是所谓的Post-Redirect-Get (PRG)模式。u003Cu002Fpu003Eu003Cpu003E简言之,当用户提交了表单后,你去执行一个u003Ci class=”chrome-extension-mutihighlight chrome-extension-mutihighlight-style-2″u003E客户端u003Cu002Fiu003E的重定向,转到提交成功信息页面。u003Cu002Fpu003Eu003Cpu003E这能避免用户按F5导致的重复提交,而其也不会出现浏览器表单重复提交的警告,也能消除按浏览器前进和后退按导致的同样问题。u003Cu002Fpu003Eu003Cpu003Eu003Cstrong toutiao-origin=”strong” class=”highlight-text”u003E3、在session中存放一个特殊标志u003Cu002Fstrongu003Eu003Cu002Fpu003Eu003Cpu003E在服务器端,生成一个唯一的标识符,将它存入session,同时将它写入表单的隐藏字段中u003Cu002Fpu003Eu003Cpu003E然后将表单页面发给浏览器,用户录入信息后点击提交u003Cu002Fpu003Eu003Cpu003E在服务器端,获取表单中隐藏字段的值,与session中的唯一标识符比较,相等说明是首次提交,就处理本次请求,然后将session中的唯一标识符移除;不相等说明是重复提交,就不再处理。u003Cu002Fpu003Eu003Cpu003Eu003Cstrong toutiao-origin=”span” class=”highlight-text”u003E4、其他借助使用header头设置缓存控制头Cache-control等方式u003Cu002Fstrongu003Eu003Cu002Fpu003Eu003Cpu003E比较复杂 不适合移动端u003Ci class=”chrome-extension-mutihighlight chrome-extension-mutihighlight-style-1″u003EAPPu003Cu002Fiu003E的应用 这里不详解u003Cu002Fpu003Eu003Cpu003Eu003Cstrong toutiao-origin=”strong” class=”highlight-text”u003E5、u003Cu002Fstrongu003Eu003Cstrong toutiao-origin=”strong” class=”highlight-text”u003E借助数据库u003Cu002Fstrongu003Eu003Cu002Fpu003Eu003Cpu003Einsert使用唯一索引 update使用 乐观锁 version版本法u003Cu002Fpu003Eu003Cpu003E这种在大数据量和高并发下效率依赖数据库硬件能力,可针对非核心业务u003Cu002Fpu003Eu003Cpu003Eu003Cstrong toutiao-origin=”strong” class=”highlight-text”u003E6、借助悲观锁u003Cu002Fstrongu003Eu003Cu002Fpu003Eu003Cpu003E使用select … for update ,这种和 synchronized 锁住先查再insert or update一样,但要避免死锁,效率也较差u003Cu002Fpu003Eu003Cpu003E针对单体 请求并发不大 可以推荐使用u003Cu002Fpu003Eu003Cpu003Eu003Cstrong toutiao-origin=”strong” class=”highlight-text”u003E7、借助本地锁(本文重点)u003Cu002Fstrongu003Eu003Cu002Fpu003Eu003Cpu003E原理:u003Cu002Fpu003Eu003Cpu003E使用了 ConcurrentHashMap 并发容器 putIfAbsent 方法,和 ScheduledThreadPoolExecutor 定时任务u003Cu002Fpu003Eu003Cpu003E也可以使用guava cache的机制, gauva中有配有缓存的有效时间也是可以的key的生成 u003Cu002Fpu003Eu003Cpu003EContent-MD5 u003Cu002Fpu003Eu003Cpu003EContent-MD5 是指 Body 的 MD5 值,只有当 Body 非Form表单时才计算MD5,计算方式直接将参数和参数名称统一加密MD5u003Cu002Fpu003Eu003Cpu003EMD5在一定范围类认为是唯一的 近似唯一 当然在低并发的情况下足够了u003Cu002Fpu003Eu003Cpu003E本地锁只适用于单机部署的应用.u003Cu002Fpu003Eu003Cpu003Eu003Cu002Fpu003Eu003Ch1 toutiao-origin=”h3″u003E①配置注解u003Cu002Fh1u003Eu003Cpreu003Eu003Ccodeu003E@Target(ElementType.METHOD)u003Cu002Fcodeu003Eu003Ccodeu003E@Retention(RetentionPolicy.RUNTIME)u003Cu002Fcodeu003Eu003Ccodeu003E@Documentedu003Cu002Fcodeu003Eu003Ccodeu003Epublic @interface Resubmit {u003Cu002Fcodeu003Eu003Cbru003Eu003Ccodeu003E u002F**u003Cu002Fcodeu003Eu003Ccodeu003E * 延时时间 在延时多久后可以再次提交u003Cu002Fcodeu003Eu003Ccodeu003E *u003Cu002Fcodeu003Eu003Ccodeu003E * @return Time unit is one secondu003Cu002Fcodeu003Eu003Ccodeu003E *u002Fu003Cu002Fcodeu003Eu003Ccodeu003E int delaySeconds default 20;u003Cu002Fcodeu003Eu003Ccodeu003E}u003Cu002Fcodeu003Eu003Cu002Fpreu003Eu003Cpu003Eu003Cu002Fpu003Eu003Ch1 toutiao-origin=”h3″u003E②实例化锁u003Cu002Fh1u003Eu003Cpreu003Eu003Ccodeu003Eu002F**u003Cu002Fcodeu003Eu003Ccodeu003E * @author lijingu003Cu002Fcodeu003Eu003Ccodeu003E * 重复提交锁u003Cu002Fcodeu003Eu003Ccodeu003E *u002Fu003Cu002Fcodeu003Eu003Ccodeu003E@Slf4ju003Cu002Fcodeu003Eu003Ccodeu003Epublic final class ResubmitLock {u003Cu002Fcodeu003Eu003Cbru003Eu003Cbru003Eu003Ccodeu003E private static final ConcurrentHashMap LOCK_CACHE = new ConcurrentHashMap<>(200);u003Cu002Fcodeu003Eu003Ccodeu003E private static final ScheduledThreadPoolExecutor EXECUTOR = new ScheduledThreadPoolExecutor(5, new ThreadPoolExecutor.DiscardPolicy);u003Cu002Fcodeu003Eu003Cbru003Eu003Cbru003Eu003Ccodeu003E u002Fu002F private static final Cache CACHES = CacheBuilder.newBuilderu003Cu002Fcodeu003Eu003Ccodeu003E u002Fu002F 最大缓存 100 个u003Cu002Fcodeu003Eu003Ccodeu003E u002Fu002F .maximumSize(1000)u003Cu002Fcodeu003Eu003Ccodeu003E u002Fu002F 设置写缓存后 5 秒钟过期u003Cu002Fcodeu003Eu003Ccodeu003E u002Fu002F .expireAfterWrite(5, TimeUnit.SECONDS)u003Cu002Fcodeu003Eu003Ccodeu003E u002Fu002F .build;u003Cu002Fcodeu003Eu003Cbru003Eu003Cbru003Eu003Ccodeu003E private ResubmitLock {u003Cu002Fcodeu003Eu003Ccodeu003E }u003Cu002Fcodeu003Eu003Cbru003Eu003Ccodeu003E u002F**u003Cu002Fcodeu003Eu003Ccodeu003E * 静态内部类 单例模式u003Cu002Fcodeu003Eu003Ccodeu003E *u003Cu002Fcodeu003Eu003Ccodeu003E * @returnu003Cu002Fcodeu003Eu003Ccodeu003E *u002Fu003Cu002Fcodeu003Eu003Ccodeu003E private static class SingletonInstance {u003Cu002Fcodeu003Eu003Ccodeu003E private static final ResubmitLock INSTANCE = new ResubmitLock;u003Cu002Fcodeu003Eu003Ccodeu003E }u003Cu002Fcodeu003Eu003Cbru003Eu003Ccodeu003E public static ResubmitLock getInstance {u003Cu002Fcodeu003Eu003Ccodeu003E return SingletonInstance.INSTANCE;u003Cu002Fcodeu003Eu003Ccodeu003E }u003Cu002Fcodeu003Eu003Cbru003Eu003Cbru003Eu003Ccodeu003E public static String handleKey(String param) {u003Cu002Fcodeu003Eu003Ccodeu003E return DigestUtils.md5Hex(param == ? “” : param);u003Cu002Fcodeu003Eu003Ccodeu003E }u003Cu002Fcodeu003Eu003Cbru003Eu003Ccodeu003E u002F**u003Cu002Fcodeu003Eu003Ccodeu003E * 加锁 putIfAbsent 是原子操作保证线程安全u003Cu002Fcodeu003Eu003Ccodeu003E *u003Cu002Fcodeu003Eu003Ccodeu003E * @param key 对应的keyu003Cu002Fcodeu003Eu003Ccodeu003E * @param valueu003Cu002Fcodeu003Eu003Ccodeu003E * @returnu003Cu002Fcodeu003Eu003Ccodeu003E *u002Fu003Cu002Fcodeu003Eu003Ccodeu003E public boolean lock(final String key, Object value) {u003Cu002Fcodeu003Eu003Ccodeu003E return Objects.is(LOCK_CACHE.putIfAbsent(key, value));u003Cu002Fcodeu003Eu003Ccodeu003E }u003Cu002Fcodeu003Eu003Cbru003Eu003Ccodeu003E u002F**u003Cu002Fcodeu003Eu003Ccodeu003E * 延时释放锁 用以控制短时间内的重复提交u003Cu002Fcodeu003Eu003Ccodeu003E *u003Cu002Fcodeu003Eu003Ccodeu003E * @param lock 是否需要解锁u003Cu002Fcodeu003Eu003Ccodeu003E * @param key 对应的keyu003Cu002Fcodeu003Eu003Ccodeu003E * @param delaySeconds 延时时间u003Cu002Fcodeu003Eu003Ccodeu003E *u002Fu003Cu002Fcodeu003Eu003Ccodeu003E public void unLock(final boolean lock, final String key, final int delaySeconds) {u003Cu002Fcodeu003Eu003Ccodeu003E if (lock) {u003Cu002Fcodeu003Eu003Ccodeu003E EXECUTOR.schedule( -> {u003Cu002Fcodeu003Eu003Ccodeu003E LOCK_CACHE.remove(key);u003Cu002Fcodeu003Eu003Ccodeu003E }, delaySeconds, TimeUnit.SECONDS);u003Cu002Fcodeu003Eu003Ccodeu003E }u003Cu002Fcodeu003Eu003Ccodeu003E }u003Cu002Fcodeu003Eu003Ccodeu003E}u003Cu002Fcodeu003Eu003Cu002Fpreu003Eu003Cpu003Eu003Cu002Fpu003Eu003Ch1 toutiao-origin=”h3″u003E③AOP 切面u003Cu002Fh1u003Eu003Cpreu003Eu003Ccodeu003E@Log4ju003Cu002Fcodeu003Eu003Ccodeu003E@Aspectu003Cu002Fcodeu003Eu003Ccodeu003E@Componentu003Cu002Fcodeu003Eu003Ccodeu003Epublic class ResubmitDataAspect {u003Cu002Fcodeu003Eu003Cbru003Eu003Ccodeu003E private final static String DATA = “data”;u003Cu002Fcodeu003Eu003Ccodeu003E private final static Object PRESENT = new Object;u003Cu002Fcodeu003Eu003Cbru003Eu003Ccodeu003E @Around(“@annotation(comu003Ci class=”chrome-extension-mutihighlight chrome-extension-mutihighlight-style-5″u003E.cnu003Cu002Fiu003E.xxxu003Ci class=”chrome-extension-mutihighlight chrome-extension-mutihighlight-style-4″u003E.comu003Cu002Fiu003Emon.annotation.Resubmit)”)u003Cu002Fcodeu003Eu003Ccodeu003E public Object handleResubmit(ProceedingJoinPoint joinPoint) throws Throwable {u003Cu002Fcodeu003Eu003Ccodeu003E Method method = ((MethodSignature) joinPoint.getSignature).getMethod;u003Cu002Fcodeu003Eu003Ccodeu003E u002Fu002F获取注解信息u003Cu002Fcodeu003Eu003Ccodeu003E Resubmit annotation = method.getAnnotation(Resubmit.class);u003Cu002Fcodeu003Eu003Ccodeu003E int delaySeconds = annotation.delaySeconds;u003Cu002Fcodeu003Eu003Ccodeu003E Object pointArgs = joinPoint.getArgs;u003Cu002Fcodeu003Eu003Ccodeu003E String key = “”;u003Cu002Fcodeu003Eu003Ccodeu003E u002Fu002F获取第一个参数u003Cu002Fcodeu003Eu003Ccodeu003E Object firstParam = pointArgs[0];u003Cu002Fcodeu003Eu003Ccodeu003E if (firstParam instanceof RequestDTO) {u003Cu002Fcodeu003Eu003Ccodeu003E u002Fu002F解析参数u003Cu002Fcodeu003Eu003Ccodeu003E JSONObject requestDTO = JSONObject.parseObject(firstParam.toString);u003Cu002Fcodeu003Eu003Ccodeu003E JSONObject data = JSONObject.parseObject(requestDTO.getString(DATA));u003Cu002Fcodeu003Eu003Ccodeu003E if (data != ) {u003Cu002Fcodeu003Eu003Ccodeu003E StringBuffer sb = new StringBuffer;u003Cu002Fcodeu003Eu003Ccodeu003E data.forEach((k, v) -> {u003Cu002Fcodeu003Eu003Ccodeu003E sb.u003Ci class=”chrome-extension-mutihighlight chrome-extension-mutihighlight-style-1″u003Eappu003Cu002Fiu003Eend(v);u003Cu002Fcodeu003Eu003Ccodeu003E });u003Cu002Fcodeu003Eu003Ccodeu003E u002Fu002F生成加密参数 使用了content_MD5的加密方式u003Cu002Fcodeu003Eu003Ccodeu003E key = ResubmitLock.handleKey(sb.toString);u003Cu002Fcodeu003Eu003Ccodeu003E }u003Cu002Fcodeu003Eu003Ccodeu003E }u003Cu002Fcodeu003Eu003Ccodeu003E u002Fu002F执行锁u003Cu002Fcodeu003Eu003Ccodeu003E boolean lock = false;u003Cu002Fcodeu003Eu003Ccodeu003E try {u003Cu002Fcodeu003Eu003Ccodeu003E u002Fu002F设置解锁keyu003Cu002Fcodeu003Eu003Ccodeu003E lock = ResubmitLock.getInstance.lock(key, PRESENT);u003Cu002Fcodeu003Eu003Ccodeu003E if (lock) {u003Cu002Fcodeu003Eu003Ccodeu003E u002Fu002F放行u003Cu002Fcodeu003Eu003Ccodeu003E return joinPoint.proceed;u003Cu002Fcodeu003Eu003Ccodeu003E } else {u003Cu002Fcodeu003Eu003Ccodeu003E u002Fu002F响应重复提交异常u003Cu002Fcodeu003Eu003Ccodeu003E return new ResponseDTO<>(ResponseCode.REPEAT_SUBMIT_OPERATION_EXCEPTION);u003Cu002Fcodeu003Eu003Ccodeu003E }u003Cu002Fcodeu003Eu003Ccodeu003E } finally {u003Cu002Fcodeu003Eu003Ccodeu003E u002Fu002F设置解锁key和解锁时间u003Cu002Fcodeu003Eu003Ccodeu003E ResubmitLock.getInstance.unLock(lock, key, delaySeconds);u003Cu002Fcodeu003Eu003Ccodeu003E }u003Cu002Fcodeu003Eu003Ccodeu003E }u003Cu002Fcodeu003Eu003Ccodeu003E}u003Cu002Fcodeu003Eu003Cu002Fpreu003Eu003Cpu003Eu003Cu002Fpu003Eu003Ch1 toutiao-origin=”h3″u003E④注解使用案例u003Cu002Fh1u003Eu003Cpreu003Eu003Ccodeu003E@ApiOperation(value = “保存我的帖子接口”, notes = “保存我的帖子接口”)u003Cu002Fcodeu003Eu003Ccodeu003E@PostMu003Ci class=”chrome-extension-mutihighlight chrome-extension-mutihighlight-style-1″u003Eappu003Cu002Fiu003Eing(“u002Fpostsu002Fsave”)u003Cu002Fcodeu003Eu003Ccodeu003E@Resubmit(delaySeconds = 10)u003Cu002Fcodeu003Eu003Ccodeu003Epublic ResponseDTO saveBbsPosts(@RequestBody @Validated RequestDTO requestDto) {u003Cu002Fcodeu003Eu003Ccodeu003E return bbsPostsBizService.saveBbsPosts(requestDto);u003Cu002Fcodeu003Eu003Ccodeu003E}u003Cu002Fcodeu003Eu003Cu002Fpreu003Eu003Cpu003E以上就是本地锁的方式进行的幂等提交 使用了Content-MD5 进行加密 只要参数不变,参数加密 密值不变,key存在就阻止提交u003Cu002Fpu003Eu003Cpu003E当然也可以使用 一些其他签名校验 在某一次提交时先 生成固定签名 提交到后端 根据后端解析统一的签名作为 每次提交的验证token 去缓存中处理即可.u003Cu002Fpu003Eu003Cpu003Eu003Cstrong toutiao-origin=”span” class=”highlight-text”u003E8、借助分布式redis锁 (参考其他)u003Cu002Fstrongu003Eu003Cu002Fpu003Eu003Cpu003E在 pom.xml 中添u003Ci class=”chrome-extension-mutihighlight chrome-extension-mutihighlight-style-5″u003E加上u003Cu002Fiu003E starter-web、starter-aop、starter-data-redis 的依赖即可u003Cu002Fpu003Eu003Cpreu003Eu003Ccodeu003E<dependencies>u003Cu002Fcodeu003Eu003Ccodeu003E <dependency>u003Cu002Fcodeu003Eu003Ccodeu003E <groupId>org.springframework.bootgroupId>u003Cu002Fcodeu003Eu003Ccodeu003E <artifactId>spring-boot-starter-webartifactId>u003Cu002Fcodeu003Eu003Ccodeu003E dependency>u003Cu002Fcodeu003Eu003Ccodeu003E <dependency>u003Cu002Fcodeu003Eu003Ccodeu003E <groupId>org.springframework.bootgroupId>u003Cu002Fcodeu003Eu003Ccodeu003E <artifactId>spring-boot-starter-aopartifactId>u003Cu002Fcodeu003Eu003Ccodeu003E dependency>u003Cu002Fcodeu003Eu003Ccodeu003E <dependency>u003Cu002Fcodeu003Eu003Ccodeu003E <groupId>org.springframework.bootgroupId>u003Cu002Fcodeu003Eu003Ccodeu003E <artifactId>spring-boot-starter-data-redisartifactId>u003Cu002Fcodeu003Eu003Ccodeu003E dependency>u003Cu002Fcodeu003Eu003Ccodeu003Edependencies>u003Cu002Fcodeu003Eu003Cu002Fpreu003Eu003Cpu003E属性配置 在 u003Ci class=”chrome-extension-mutihighlight chrome-extension-mutihighlight-style-1″u003Eappu003Cu002Fiu003Elication.properites 资源文件中添加 redis 相关的配置项u003Cu002Fpu003Eu003Cpreu003Eu003Ccodeu003Espring.redis.host=locau003Ci class=”chrome-extension-mutihighlight chrome-extension-mutihighlight-style-6″u003Elhu003Cu002Fiu003Eostu003Cu002Fcodeu003Eu003Ccodeu003Espring.redis.port=6379u003Cu002Fcodeu003Eu003Ccodeu003Espring.redis.password=123456u003Cu002Fcodeu003Eu003Cu002Fpreu003Eu003Cpu003Eu003Cstrongu003E主要实现方式:u003Cu002Fstrongu003Eu003Cu002Fpu003Eu003Cpu003E熟悉 Redis 的朋友都知道它是线程安全的,我们利用它的特性可以很轻松的实现一个分布式锁,如 opsForValue.setIfAbsent(key,value)u003Cu002Fpu003Eu003Cpu003E它的作用就是如果缓存中没有当前 Key 则进行缓存同时返回 true 反之亦然;u003Cu002Fpu003Eu003Cpu003E当缓存后给 key 在设置个过期时间,防止因为系统崩溃而导致锁迟迟不释放形成死锁;u003Cu002Fpu003Eu003Cpu003E那么我们是不是可以这样认为当返回 true 我们认为它获取到锁了,在锁未释放的时候我们进行异常的抛出…u003Cu002Fpu003Eu003Cpreu003Eu003Ccodeu003E@Aspectu003Cu002Fcodeu003Eu003Ccodeu003E@Configurationu003Cu002Fcodeu003Eu003Ccodeu003Epublic class LockMethodInterceptor {u003Cu002Fcodeu003Eu003Cbru003Eu003Ccodeu003E @Autowiredu003Cu002Fcodeu003Eu003Ccodeu003E public LockMethodInterceptor(RedisLockHelper redisLockHelper, CacheKeyGenerator cacheKeyGenerator) {u003Cu002Fcodeu003Eu003Ccodeu003E this.redisLockHelper = redisLockHelper;u003Cu002Fcodeu003Eu003Ccodeu003E this.cacheKeyGenerator = cacheKeyGenerator;u003Cu002Fcodeu003Eu003Ccodeu003E }u003Cu002Fcodeu003Eu003Cbru003Eu003Ccodeu003E private final RedisLockHelper redisLockHelper;u003Cu002Fcodeu003Eu003Ccodeu003E private final CacheKeyGenerator cacheKeyGenerator;u003Cu002Fcodeu003Eu003Cbru003Eu003Cbru003Eu003Ccodeu003E @Around(“execution(public * *(..)) && @annotation(com.battcn.annotation.CacheLock)”)u003Cu002Fcodeu003Eu003Ccodeu003E public Object interceptor(ProceedingJoinPoint pjp) {u003Cu002Fcodeu003Eu003Ccodeu003E MethodSignature signature = (MethodSignature) pjp.getSignature;u003Cu002Fcodeu003Eu003Ccodeu003E Method method = signature.getMethod;u003Cu002Fcodeu003Eu003Ccodeu003E CacheLock lock = method.getAnnotation(CacheLock.class);u003Cu002Fcodeu003Eu003Ccodeu003E if (StringUtils.isEmpty(lock.prefix)) {u003Cu002Fcodeu003Eu003Ccodeu003E throw new RuntimeException(“lock key don’t …”);u003Cu002Fcodeu003Eu003Ccodeu003E }u003Cu002Fcodeu003Eu003Ccodeu003E final String lockKey = cacheKeyGenerator.getLockKey(pjp);u003Cu002Fcodeu003Eu003Ccodeu003E String value = UUID.randomUUID.toString;u003Cu002Fcodeu003Eu003Ccodeu003E try {u003Cu002Fcodeu003Eu003Ccodeu003E u002Fu002F 假设上锁成功,但是设置过期时间失效,以后拿到的都是 falseu003Cu002Fcodeu003Eu003Ccodeu003E final boolean success = redisLockHelper.lock(lockKey, value, lock.expire, lock.timeUnit);u003Cu002Fcodeu003Eu003Ccodeu003E if (!success) {u003Cu002Fcodeu003Eu003Ccodeu003E throw new RuntimeException(“重复提交”);u003Cu002Fcodeu003Eu003Ccodeu003E }u003Cu002Fcodeu003Eu003Ccodeu003E try {u003Cu002Fcodeu003Eu003Ccodeu003E return pjp.proceed;u003Cu002Fcodeu003Eu003Ccodeu003E } catch (Throwable throwable) {u003Cu002Fcodeu003Eu003Ccodeu003E throw new RuntimeException(“系统异常”);u003Cu002Fcodeu003Eu003Ccodeu003E }u003Cu002Fcodeu003Eu003Ccodeu003E } finally {u003Cu002Fcodeu003Eu003Ccodeu003E u002Fu002F TODO 如果演示的话需要注释该代码;实际应该放开u003Cu002Fcodeu003Eu003Ccodeu003E redisLockHelper.unlock(lockKey, value);u003Cu002Fcodeu003Eu003Ccodeu003E }u003Cu002Fcodeu003Eu003Ccodeu003E }u003Cu002Fcodeu003Eu003Ccodeu003E}u003Cu002Fcodeu003Eu003Cu002Fpreu003Eu003Cpu003ERedisLockHelper 通过封装成 API 方式调用,灵活度更加高u003Cu002Fpu003Eu003Cpreu003Eu003Ccodeu003E@Configurationu003Cu002Fcodeu003Eu003Ccodeu003E@AutoConfigureAfter(RedisAutoConfiguration.class)u003Cu002Fcodeu003Eu003Ccodeu003Epublic class RedisLockHelper {u003Cu002Fcodeu003Eu003Cbru003Eu003Cbru003Eu003Ccodeu003E private static final String DELIMITER = “|”;u003Cu002Fcodeu003Eu003Cbru003Eu003Ccodeu003E u002F**u003Cu002Fcodeu003Eu003Ccodeu003E * 如果要求比较高可以通过注入的方式分配u003Cu002Fcodeu003Eu003Ccodeu003E *u002Fu003Cu002Fcodeu003Eu003Ccodeu003E private static final ScheduledExecutorService EXECUTOR_SERVICE = Executors.newScheduledThreadPool(10);u003Cu002Fcodeu003Eu003Cbru003Eu003Ccodeu003E private final StringRedisTemplate stringRedisTemplate;u003Cu002Fcodeu003Eu003Cbru003Eu003Ccodeu003E public RedisLockHelper(StringRedisTemplate stringRedisTemplate) {u003Cu002Fcodeu003Eu003Ccodeu003E this.stringRedisTemplate = stringRedisTemplate;u003Cu002Fcodeu003Eu003Ccodeu003E }u003Cu002Fcodeu003Eu003Cbru003Eu003Ccodeu003E u002F**u003Cu002Fcodeu003Eu003Ccodeu003E * 获取锁(存在死锁风险)u003Cu002Fcodeu003Eu003Ccodeu003E *u003Cu002Fcodeu003Eu003Ccodeu003E * @param lockKey lockKeyu003Cu002Fcodeu003Eu003Ccodeu003E * @param value valueu003Cu002Fcodeu003Eu003Ccodeu003E * @param time 超时时间u003Cu002Fcodeu003Eu003Ccodeu003E * @param unit 过期单位u003Cu002Fcodeu003Eu003Ccodeu003E * @return true or falseu003Cu002Fcodeu003Eu003Ccodeu003E *u002Fu003Cu002Fcodeu003Eu003Ccodeu003E public boolean tryLock(final String lockKey, final String value, final long time, final TimeUnit unit) {u003Cu002Fcodeu003Eu003Ccodeu003E return stringRedisTemplate.execute((RedisCallback<Boolean>) connection -> connection.set(lockKey.getBytes, value.getBytes, Expiration.from(time, unit), RedisStringCommands.SetOption.SET_IF_ABSENT));u003Cu002Fcodeu003Eu003Ccodeu003E }u003Cu002Fcodeu003Eu003Cbru003Eu003Ccodeu003E u002F**u003Cu002Fcodeu003Eu003Ccodeu003E * 获取锁u003Cu002Fcodeu003Eu003Ccodeu003E *u003Cu002Fcodeu003Eu003Ccodeu003E * @param lockKey lockKeyu003Cu002Fcodeu003Eu003Ccodeu003E * @param uuid UUIDu003Cu002Fcodeu003Eu003Ccodeu003E * @param timeout 超时时间u003Cu002Fcodeu003Eu003Ccodeu003E * @param unit 过期单位u003Cu002Fcodeu003Eu003Ccodeu003E * @return true or falseu003Cu002Fcodeu003Eu003Ccodeu003E *u002Fu003Cu002Fcodeu003Eu003Ccodeu003E public boolean lock(String lockKey, final String uuid, long timeout, final TimeUnit unit) {u003Cu002Fcodeu003Eu003Ccodeu003E final long milliseconds = Expiration.from(timeout, unit).getExpirationTimeInMilliseconds;u003Cu002Fcodeu003Eu003Ccodeu003E boolean success = stringRedisTemplate.opsForValue.setIfAbsent(lockKey, (System.currentTimeMillis + milliseconds) + DELIMITER + uuid);u003Cu002Fcodeu003Eu003Ccodeu003E if (success) {u003Cu002Fcodeu003Eu003Ccodeu003E stringRedisTemplate.expire(lockKey, timeout, TimeUnit.SECONDS);u003Cu002Fcodeu003Eu003Ccodeu003E } else {u003Cu002Fcodeu003Eu003Ccodeu003E String oldVal = stringRedisTemplate.opsForValue.getAndSet(lockKey, (System.currentTimeMillis + milliseconds) + DELIMITER + uuid);u003Cu002Fcodeu003Eu003Ccodeu003E final String oldValues = oldVal.split(Pattern.quote(DELIMITER));u003Cu002Fcodeu003Eu003Ccodeu003E if (Long.parseLong(oldValues[0]) + 1 <= System.currentTimeMillis) {u003Cu002Fcodeu003Eu003Ccodeu003E return true;u003Cu002Fcodeu003Eu003Ccodeu003E }u003Cu002Fcodeu003Eu003Ccodeu003E }u003Cu002Fcodeu003Eu003Ccodeu003E return success;u003Cu002Fcodeu003Eu003Ccodeu003E }u003Cu002Fcodeu003Eu003Cbru003Eu003Cbru003Eu003Ccodeu003E u002F**u003Cu002Fcodeu003Eu003Ccodeu003E * @see Redis Documentation: SETu003Cu002Fcodeu003Eu003Ccodeu003E *u002Fu003Cu002Fcodeu003Eu003Ccodeu003E public void unlock(String lockKey, String value) {u003Cu002Fcodeu003Eu003Ccodeu003E unlock(lockKey, value, 0, TimeUnit.MILLISECONDS);u003Cu002Fcodeu003Eu003Ccodeu003E }u003Cu002Fcodeu003Eu003Cbru003Eu003Ccodeu003E u002F**u003Cu002Fcodeu003Eu003Ccodeu003E * 延迟unlocku003Cu002Fcodeu003Eu003Ccodeu003E *u003Cu002Fcodeu003Eu003Ccodeu003E * @param lockKey keyu003Cu002Fcodeu003Eu003Ccodeu003E * @param uuid client(最好是唯一键的)u003Cu002Fcodeu003Eu003Ccodeu003E * @param delayTime 延迟时间u003Cu002Fcodeu003Eu003Ccodeu003E * @param unit 时间单位u003Cu002Fcodeu003Eu003Ccodeu003E *u002Fu003Cu002Fcodeu003Eu003Ccodeu003E public void unlock(final String lockKey, final String uuid, long delayTime, TimeUnit unit) {u003Cu002Fcodeu003Eu003Ccodeu003E if (StringUtils.isEmpty(lockKey)) {u003Cu002Fcodeu003Eu003Ccodeu003E return;u003Cu002Fcodeu003Eu003Ccodeu003E }u003Cu002Fcodeu003Eu003Ccodeu003E if (delayTime <= 0) {u003Cu002Fcodeu003Eu003Ccodeu003E doUnlock(lockKey, uuid);u003Cu002Fcodeu003Eu003Ccodeu003E } else {u003Cu002Fcodeu003Eu003Ccodeu003E EXECUTOR_SERVICE.schedule( -> doUnlock(lockKey, uuid), delayTime, unit);u003Cu002Fcodeu003Eu003Ccodeu003E }u003Cu002Fcodeu003Eu003Ccodeu003E }u003Cu002Fcodeu003Eu003Cbru003Eu003Ccodeu003E u002F**u003Cu002Fcodeu003Eu003Ccodeu003E * @param lockKey keyu003Cu002Fcodeu003Eu003Ccodeu003E * @param uuid client(最好是唯一键的)u003Cu002Fcodeu003Eu003Ccodeu003E *u002Fu003Cu002Fcodeu003Eu003Ccodeu003E private void doUnlock(final String lockKey, final String uuid) {u003Cu002Fcodeu003Eu003Ccodeu003E String val = stringRedisTemplate.opsForValue.get(lockKey);u003Cu002Fcodeu003Eu003Ccodeu003E final String values = val.split(Pattern.quote(DELIMITER));u003Cu002Fcodeu003Eu003Ccodeu003E if (values.length <= 0) {u003Cu002Fcodeu003Eu003Ccodeu003E return;u003Cu002Fcodeu003Eu003Ccodeu003E }u003Cu002Fcodeu003Eu003Ccodeu003E if (uuid.equals(values[1])) {u003Cu002Fcodeu003Eu003Ccodeu003E stringRedisTemplate.delete(lockKey);u003Cu002Fcodeu003Eu003Ccodeu003E }u003Cu002Fcodeu003Eu003Ccodeu003E }u003Cu002Fcodeu003Eu003Cbru003Eu003Ccodeu003E}u003Cu002Fcodeu003Eu003Cu002Fpreu003Eu003Cpu003Eredis的提交参照u003Cu002Fpu003Eu003Cblockquoteu003Eu003Cpu003Ehttps:u002Fu002Fblog.battcnu003Ci class=”chrome-extension-mutihighlight chrome-extension-mutihighlight-style-4″u003E.comu003Cu002Fiu003Eu002F2018u002F06u002F13u002Fspringbootu002Fv2-cache-redislocku002Fu003Cu002Fpu003Eu003Cu002Fblockquoteu003E”

原文始发于:8 种方案,帮你解决重复提交问题

主题测试文章,只做测试使用。发布者:逗乐男神i,转转请注明出处:http://www.cxybcw.com/17846.html

联系我们

13687733322

在线咨询:点击这里给我发消息

邮件:1877088071@qq.com

工作时间:周一至周五,9:30-18:30,节假日休息

QR code