有位敌人,某天忽然问磊哥:在 Java 中,避免反复提交最简略的计划是什么

这句话中蕴含了两个要害信息,第一:避免反复提交;第二:最简略

于是磊哥问他,是单机环境还是分布式环境?

失去的反馈是单机环境,那就简略了,于是磊哥就开始装*了。

话不多说,咱们先来复现这个问题。

模仿用户场景

依据敌人的反馈,大抵的场景是这样的,如下图所示:

简化的模仿代码如下(基于 Spring Boot):

import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RequestMapping("/user")@RestControllerpublic class UserController {   /**     * 被反复申请的办法     */    @RequestMapping("/add")    public String addUser(String id) {        // 业务代码...        System.out.println("增加用户ID:" + id);        return "执行胜利!";    }}

于是磊哥就想到:通过前、后端别离拦挡的形式来解决数据反复提交的问题。

前端拦挡

前端拦挡是指通过 HTML 页面来拦挡反复申请,比方在用户点击完“提交”按钮后,咱们能够把按钮设置为不可用或者暗藏状态。

执行成果如下图所示:

前端拦挡的实现代码:

<html><script>    function subCli(){        // 按钮设置为不可用        document.getElementById("btn_sub").disabled="disabled";        document.getElementById("dv1").innerText = "按钮被点击了~";    }</script><body style="margin-top: 100px;margin-left: 100px;">    <input id="btn_sub" type="button"  value=" 提 交 "  onclick="subCli()">    <div id="dv1" style="margin-top: 80px;"></div></body></html>

但前端拦挡有一个致命的问题,如果是懂行的程序员或非法用户能够间接绕过前端页面,通过模仿申请来反复提交申请,比方充值了 100 元,反复提交了 10 次变成了 1000 元(霎时发现了一个致富的好方法)。

所以除了前端拦挡一部分失常的误操作之外,后端的拦挡也是必不可少。

后端拦挡

后端拦挡的实现思路是在办法执行之前,先判断此业务是否曾经执行过,如果执行过则不再执行,否则就失常执行。

咱们将申请的业务 ID 存储在内存中,并且通过增加互斥锁来保障多线程下的程序执行平安,大体实现思路如下图所示:

然而,将数据存储在内存中,最简略的办法就是应用 HashMap 存储,或者是应用 Guava Cache 也是同样的成果,但很显然 HashMap 能够更快的实现性能,所以咱们先来实现一个 HashMap 的防重(避免反复)版本。

1.根底版——HashMap

import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import java.util.HashMap;import java.util.Map;/** * 一般 Map 版本 */@RequestMapping("/user")@RestControllerpublic class UserController3 {    // 缓存 ID 汇合    private Map<String, Integer> reqCache = new HashMap<>();    @RequestMapping("/add")    public String addUser(String id) {        // 非空判断(疏忽)...        synchronized (this.getClass()) {            // 反复申请判断            if (reqCache.containsKey(id)) {                // 反复申请                System.out.println("请勿反复提交!!!" + id);                return "执行失败";            }            // 存储申请 ID            reqCache.put(id, 1);        }        // 业务代码...        System.out.println("增加用户ID:" + id);        return "执行胜利!";    }}

实现成果如下图所示:

存在的问题:此实现形式有一个致命的问题,因为 HashMap 是有限增长的,因而它会占用越来越多的内存,并且随着 HashMap 数量的减少查找的速度也会升高,所以咱们须要实现一个能够主动“革除”过期数据的实现计划。

2.优化版——固定大小的数组

此版本解决了 HashMap 有限增长的问题,它应用数组加下标计数器(reqCacheCounter)的形式,实现了固定数组的循环存储。

当数组存储到最初一位时,将数组的存储下标设置 0,再从头开始存储数据,实现代码如下:

import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import java.util.Arrays;@RequestMapping("/user")@RestControllerpublic class UserController {    private static String[] reqCache = new String[100]; // 申请 ID 存储汇合    private static Integer reqCacheCounter = 0; // 申请计数器(批示 ID 存储的地位)    @RequestMapping("/add")    public String addUser(String id) {        // 非空判断(疏忽)...        synchronized (this.getClass()) {            // 反复申请判断            if (Arrays.asList(reqCache).contains(id)) {                // 反复申请                System.out.println("请勿反复提交!!!" + id);                return "执行失败";            }            // 记录申请 ID            if (reqCacheCounter >= reqCache.length) reqCacheCounter = 0; // 重置计数器            reqCache[reqCacheCounter] = id; // 将 ID 保留到缓存            reqCacheCounter++; // 下标往后移一位        }        // 业务代码...        System.out.println("增加用户ID:" + id);        return "执行胜利!";    }}

3.扩大版——双重检测锁(DCL)

上一种实现办法将判断和增加业务,都放入 synchronized 中进行加锁操作,这样显然性能不是很高,于是咱们能够应用单例中驰名的 DCL(Double Checked Locking,双重检测锁)来优化代码的执行效率,实现代码如下:

import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import java.util.Arrays;@RequestMapping("/user")@RestControllerpublic class UserController {    private static String[] reqCache = new String[100]; // 申请 ID 存储汇合    private static Integer reqCacheCounter = 0; // 申请计数器(批示 ID 存储的地位)    @RequestMapping("/add")    public String addUser(String id) {        // 非空判断(疏忽)...        // 反复申请判断        if (Arrays.asList(reqCache).contains(id)) {            // 反复申请            System.out.println("请勿反复提交!!!" + id);            return "执行失败";        }        synchronized (this.getClass()) {            // 双重查看锁(DCL,double checked locking)进步程序的执行效率            if (Arrays.asList(reqCache).contains(id)) {                // 反复申请                System.out.println("请勿反复提交!!!" + id);                return "执行失败";            }            // 记录申请 ID            if (reqCacheCounter >= reqCache.length) reqCacheCounter = 0; // 重置计数器            reqCache[reqCacheCounter] = id; // 将 ID 保留到缓存            reqCacheCounter++; // 下标往后移一位        }        // 业务代码...        System.out.println("增加用户ID:" + id);        return "执行胜利!";    }}
留神:DCL 实用于反复提交频繁比拟高的业务场景,对于相同的业务场景下 DCL 并不实用。

4.欠缺版——LRUMap

下面的代码根本曾经实现了反复数据的拦挡,但显然不够简洁和优雅,比方下标计数器的申明和业务解决等,但值得庆幸的是 Apache 为咱们提供了一个 commons-collections 的框架,外面有一个十分好用的数据结构 LRUMap 能够保留指定数量的固定的数据,并且它会依照 LRU 算法,帮你革除最不罕用的数据。

小贴士:LRU 是 Least Recently Used 的缩写,即最近起码应用,是一种罕用的数据淘汰算法,抉择最近最久未应用的数据予以淘汰。

首先,咱们先来增加 Apache commons collections 的援用:

 <!-- 汇合工具类 apache commons collections --><!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 --><dependency>  <groupId>org.apache.commons</groupId>  <artifactId>commons-collections4</artifactId>  <version>4.4</version></dependency>

实现代码如下:

import org.apache.commons.collections4.map.LRUMap;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RequestMapping("/user")@RestControllerpublic class UserController {    // 最大容量 100 个,依据 LRU 算法淘汰数据的 Map 汇合    private LRUMap<String, Integer> reqCache = new LRUMap<>(100);    @RequestMapping("/add")    public String addUser(String id) {        // 非空判断(疏忽)...        synchronized (this.getClass()) {            // 反复申请判断            if (reqCache.containsKey(id)) {                // 反复申请                System.out.println("请勿反复提交!!!" + id);                return "执行失败";            }            // 存储申请 ID            reqCache.put(id, 1);        }        // 业务代码...        System.out.println("增加用户ID:" + id);        return "执行胜利!";    }}

应用了 LRUMap 之后,代码显然简洁了很多。

5.最终版——封装

以上都是办法级别的实现计划,然而在理论的业务中,咱们可能有很多的办法都须要防重,那么接下来咱们就来封装一个公共的办法,以供所有类应用:

import org.apache.commons.collections4.map.LRUMap;/** * 幂等性判断 */public class IdempotentUtils {    // 依据 LRU(Least Recently Used,最近起码应用)算法淘汰数据的 Map 汇合,最大容量 100 个    private static LRUMap<String, Integer> reqCache = new LRUMap<>(100);    /**     * 幂等性判断     * @return     */    public static boolean judge(String id, Object lockClass) {        synchronized (lockClass) {            // 反复申请判断            if (reqCache.containsKey(id)) {                // 反复申请                System.out.println("请勿反复提交!!!" + id);                return false;            }            // 非反复申请,存储申请 ID            reqCache.put(id, 1);        }        return true;    }}

调用代码如下:

import com.example.idempote.util.IdempotentUtils;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RequestMapping("/user")@RestControllerpublic class UserController4 {    @RequestMapping("/add")    public String addUser(String id) {        // 非空判断(疏忽)...        // -------------- 幂等性调用(开始) --------------        if (!IdempotentUtils.judge(id, this.getClass())) {            return "执行失败";        }        // -------------- 幂等性调用(完结) --------------        // 业务代码...        System.out.println("增加用户ID:" + id);        return "执行胜利!";    }}
小贴士:个别状况下代码写到这里就完结了,但想要更简洁也是能够实现的,你能够通过自定义注解,将业务代码写到注解中,须要调用的办法只须要写一行注解就能够避免数据反复提交了,老铁们能够自行尝试一下(须要磊哥撸一篇的,评论区留言 666)。

扩大常识——LRUMap 实现原理剖析

既然 LRUMap 如此弱小,咱们就来看看它是如何实现的。

LRUMap 的实质是持有头结点的环回双链表构造,它的存储构造如下:

AbstractLinkedMap.LinkEntry entry;

当调用查询方法时,会将应用的元素放在双链表 header 的前一个地位,源码如下:

public V get(Object key, boolean updateToMRU) {    LinkEntry<K, V> entry = this.getEntry(key);    if (entry == null) {        return null;    } else {        if (updateToMRU) {            this.moveToMRU(entry);        }        return entry.getValue();    }}protected void moveToMRU(LinkEntry<K, V> entry) {    if (entry.after != this.header) {        ++this.modCount;        if (entry.before == null) {            throw new IllegalStateException("Entry.before is null. This should not occur if your keys are immutable, and you have used synchronization properly.");        }        entry.before.after = entry.after;        entry.after.before = entry.before;        entry.after = this.header;        entry.before = this.header.before;        this.header.before.after = entry;        this.header.before = entry;    } else if (entry == this.header) {        throw new IllegalStateException("Can't move header to MRU This should not occur if your keys are immutable, and you have used synchronization properly.");    }}

如果新增元素时,容量满了就会移除 header 的后一个元素,增加源码如下:

 protected void addMapping(int hashIndex, int hashCode, K key, V value) {     // 判断容器是否已满         if (this.isFull()) {         LinkEntry<K, V> reuse = this.header.after;         boolean removeLRUEntry = false;         if (!this.scanUntilRemovable) {             removeLRUEntry = this.removeLRU(reuse);         } else {             while(reuse != this.header && reuse != null) {                 if (this.removeLRU(reuse)) {                     removeLRUEntry = true;                     break;                 }                 reuse = reuse.after;             }             if (reuse == null) {                 throw new IllegalStateException("Entry.after=null, header.after=" + this.header.after + " header.before=" + this.header.before + " key=" + key + " value=" + value + " size=" + this.size + " maxSize=" + this.maxSize + " This should not occur if your keys are immutable, and you have used synchronization properly.");             }         }         if (removeLRUEntry) {             if (reuse == null) {                 throw new IllegalStateException("reuse=null, header.after=" + this.header.after + " header.before=" + this.header.before + " key=" + key + " value=" + value + " size=" + this.size + " maxSize=" + this.maxSize + " This should not occur if your keys are immutable, and you have used synchronization properly.");             }             this.reuseMapping(reuse, hashIndex, hashCode, key, value);         } else {             super.addMapping(hashIndex, hashCode, key, value);         }     } else {         super.addMapping(hashIndex, hashCode, key, value);     } }

判断容量的源码:

public boolean isFull() {  return size >= maxSize;}

**
容量未满就间接增加数据:

super.addMapping(hashIndex, hashCode, key, value);

如果容量满了,就调用 reuseMapping 办法应用 LRU 算法对数据进行革除。

综合来说:LRUMap 的实质是持有头结点的环回双链表构造,当应用元素时,就将该元素放在双链表 header 的前一个地位,在新增元素时,如果容量满了就会移除 header 的后一个元素

总结

本文讲了避免数据反复提交的 6 种办法,首先是前端的拦挡,通过暗藏和设置按钮的不可用来屏蔽失常操作下的反复提交。但为了防止非正常渠道的反复提交,咱们又实现了 5 个版本的后端拦挡:HashMap 版、固定数组版、双重检测锁的数组版、LRUMap 版和 LRUMap 的封装版。

非凡阐明:本文所有的内容仅实用于单机环境下的反复数据拦挡,如果是分布式环境须要配合数据库或 Redis 来实现,想看分布式反复数据拦挡的老铁们,请给磊哥一个「」,如果点赞超过 100 个,咱们更新分布式环境下反复数据的解决计划,谢谢你。

参考 & 鸣谢

https://blog.csdn.net/fenglllle/article/details/82659576

关注公众号「Java中文社群」订阅更多精彩。

<image src="https://user-gold-cdn.xitu.io/2020/7/6/1732179389ab7c5c?w=344&h=344&f=jpeg&s=9375" style="zoom:75%;"></image>