成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

6種防止數據重復提交的方法!

開發 后端
本文講了防止數據重復提交的 6 種方法,首先是前端的攔截,通過隱藏和設置按鈕的不可用來屏蔽正常操作下的重復提交。但為了避免非正常渠道的重復提交,我們又實現了 5 個版本的后端攔截:HashMap 版、固定數組版、雙重檢測鎖的數組版、LRUMap 版和 LRUMap 的封裝版。

 [[334014]]

本文轉載自微信公眾號「Java中文社群」,作者老王著 。轉載本文請聯系Java中文社群公眾號。

有位朋友,某天突然問磊哥:在 Java 中,防止重復提交最簡單的方案是什么?

這句話中包含了兩個關鍵信息,第一:防止重復提交;第二:最簡單。

于是磊哥問他,是單機環境還是分布式環境?

得到的反饋是單機環境,那就簡單了,于是磊哥就開始裝*了。

話不多說,我們先來復現這個問題。

模擬用戶場景

根據朋友的反饋,大致的場景是這樣的,如下圖所示:

 

簡化的模擬代碼如下(基于 Spring Boot):

  1. import org.springframework.web.bind.annotation.RequestMapping; 
  2. import org.springframework.web.bind.annotation.RestController; 
  3.  
  4. @RequestMapping("/user"
  5. @RestController 
  6. public class UserController { 
  7.    /** 
  8.      * 被重復請求的方法 
  9.      */ 
  10.     @RequestMapping("/add"
  11.     public String addUser(String id) { 
  12.         // 業務代碼... 
  13.         System.out.println("添加用戶ID:" + id); 
  14.         return "執行成功!"
  15.     } 

于是磊哥就想到:通過前、后端分別攔截的方式來解決數據重復提交的問題。

前端攔截

前端攔截是指通過 HTML 頁面來攔截重復請求,比如在用戶點擊完“提交”按鈕后,我們可以把按鈕設置為不可用或者隱藏狀態。

執行效果如下圖所示:

 

前端攔截的實現代碼:

  1. <html> 
  2. <script> 
  3.     function subCli(){ 
  4.         // 按鈕設置為不可用 
  5.         document.getElementById("btn_sub").disabled="disabled"
  6.         document.getElementById("dv1").innerText = "按鈕被點擊了~"
  7.     } 
  8. </script> 
  9. <body style="margin-top: 100px;margin-left: 100px;"
  10.     <input id="btn_sub" type="button"  value=" 提 交 "  onclick="subCli()"
  11.     <div id="dv1" style="margin-top: 80px;"></div> 
  12. </body> 
  13. </html> 

 

但前端攔截有一個致命的問題,如果是懂行的程序員或非法用戶可以直接繞過前端頁面,通過模擬請求來重復提交請求,比如充值了 100 元,重復提交了 10 次變成了 1000 元(瞬間發現了一個致富的好辦法)。

所以除了前端攔截一部分正常的誤操作之外,后端的攔截也是必不可少。

后端攔截

后端攔截的實現思路是在方法執行之前,先判斷此業務是否已經執行過,如果執行過則不再執行,否則就正常執行。

我們將請求的業務 ID 存儲在內存中,并且通過添加互斥鎖來保證多線程下的程序執行安全,大體實現思路如下圖所示:

 

然而,將數據存儲在內存中,最簡單的方法就是使用 HashMap 存儲,或者是使用 Guava Cache 也是同樣的效果,但很顯然 HashMap 可以更快的實現功能,所以我們先來實現一個 HashMap 的防重(防止重復)版本。

1.基礎版——HashMap

  1. import org.springframework.web.bind.annotation.RequestMapping; 
  2. import org.springframework.web.bind.annotation.RestController; 
  3.  
  4. import java.util.HashMap; 
  5. import java.util.Map; 
  6.  
  7. /** 
  8.  * 普通 Map 版本 
  9.  */ 
  10. @RequestMapping("/user"
  11. @RestController 
  12. public class UserController3 { 
  13.  
  14.     // 緩存 ID 集合 
  15.     private Map<String, Integer> reqCache = new HashMap<>(); 
  16.  
  17.     @RequestMapping("/add"
  18.     public String addUser(String id) { 
  19.         // 非空判斷(忽略)... 
  20.         synchronized (this.getClass()) { 
  21.             // 重復請求判斷 
  22.             if (reqCache.containsKey(id)) { 
  23.                 // 重復請求 
  24.                 System.out.println("請勿重復提交!!!" + id); 
  25.                 return "執行失敗"
  26.             } 
  27.             // 存儲請求 ID 
  28.             reqCache.put(id, 1); 
  29.         } 
  30.         // 業務代碼... 
  31.         System.out.println("添加用戶ID:" + id); 
  32.         return "執行成功!"
  33.     } 

實現效果如下圖所示:

 

存在的問題:此實現方式有一個致命的問題,因為 HashMap 是無限增長的,因此它會占用越來越多的內存,并且隨著 HashMap 數量的增加查找的速度也會降低,所以我們需要實現一個可以自動“清除”過期數據的實現方案。

2.優化版——固定大小的數組

此版本解決了 HashMap 無限增長的問題,它使用數組加下標計數器(reqCacheCounter)的方式,實現了固定數組的循環存儲。

當數組存儲到最后一位時,將數組的存儲下標設置 0,再從頭開始存儲數據,實現代碼如下:

  1. import org.springframework.web.bind.annotation.RequestMapping; 
  2. import org.springframework.web.bind.annotation.RestController; 
  3.  
  4. import java.util.Arrays; 
  5.  
  6. @RequestMapping("/user"
  7. @RestController 
  8. public class UserController { 
  9.  
  10.     private static String[] reqCache = new String[100]; // 請求 ID 存儲集合 
  11.     private static Integer reqCacheCounter = 0; // 請求計數器(指示 ID 存儲的位置) 
  12.  
  13.     @RequestMapping("/add"
  14.     public String addUser(String id) { 
  15.         // 非空判斷(忽略)... 
  16.         synchronized (this.getClass()) { 
  17.             // 重復請求判斷 
  18.             if (Arrays.asList(reqCache).contains(id)) { 
  19.                 // 重復請求 
  20.                 System.out.println("請勿重復提交!!!" + id); 
  21.                 return "執行失敗"
  22.             } 
  23.             // 記錄請求 ID 
  24.             if (reqCacheCounter >= reqCache.length) reqCacheCounter = 0; // 重置計數器 
  25.             reqCache[reqCacheCounter] = id; // 將 ID 保存到緩存 
  26.             reqCacheCounter++; // 下標往后移一位 
  27.         } 
  28.         // 業務代碼... 
  29.         System.out.println("添加用戶ID:" + id); 
  30.         return "執行成功!"
  31.     } 

3.擴展版——雙重檢測鎖(DCL)

上一種實現方法將判斷和添加業務,都放入 synchronized 中進行加鎖操作,這樣顯然性能不是很高,于是我們可以使用單例中著名的 DCL(Double Checked Locking,雙重檢測鎖)來優化代碼的執行效率,實現代碼如下:

  1. import org.springframework.web.bind.annotation.RequestMapping; 
  2. import org.springframework.web.bind.annotation.RestController; 
  3.  
  4. import java.util.Arrays; 
  5.  
  6. @RequestMapping("/user"
  7. @RestController 
  8. public class UserController { 
  9.  
  10.     private static String[] reqCache = new String[100]; // 請求 ID 存儲集合 
  11.     private static Integer reqCacheCounter = 0; // 請求計數器(指示 ID 存儲的位置) 
  12.  
  13.     @RequestMapping("/add"
  14.     public String addUser(String id) { 
  15.         // 非空判斷(忽略)... 
  16.         // 重復請求判斷 
  17.         if (Arrays.asList(reqCache).contains(id)) { 
  18.             // 重復請求 
  19.             System.out.println("請勿重復提交!!!" + id); 
  20.             return "執行失敗"
  21.         } 
  22.         synchronized (this.getClass()) { 
  23.             // 雙重檢查鎖(DCL,double checked locking)提高程序的執行效率 
  24.             if (Arrays.asList(reqCache).contains(id)) { 
  25.                 // 重復請求 
  26.                 System.out.println("請勿重復提交!!!" + id); 
  27.                 return "執行失敗"
  28.             } 
  29.             // 記錄請求 ID 
  30.             if (reqCacheCounter >= reqCache.length) reqCacheCounter = 0; // 重置計數器 
  31.             reqCache[reqCacheCounter] = id; // 將 ID 保存到緩存 
  32.             reqCacheCounter++; // 下標往后移一位 
  33.         } 
  34.         // 業務代碼... 
  35.         System.out.println("添加用戶ID:" + id); 
  36.         return "執行成功!"
  37.     } 

注意:DCL 適用于重復提交頻繁比較高的業務場景,對于相反的業務場景下 DCL 并不適用。

4.完善版——LRUMap

上面的代碼基本已經實現了重復數據的攔截,但顯然不夠簡潔和優雅,比如下標計數器的聲明和業務處理等,但值得慶幸的是 Apache 為我們提供了一個 commons-collections 的框架,里面有一個非常好用的數據結構 LRUMap 可以保存指定數量的固定的數據,并且它會按照 LRU 算法,幫你清除最不常用的數據。

小貼士:LRU 是 Least Recently Used 的縮寫,即最近最少使用,是一種常用的數據淘汰算法,選擇最近最久未使用的數據予以淘汰。

首先,我們先來添加 Apache commons collections 的引用:

  1.  <!-- 集合工具類 apache commons collections --> 
  2. <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 --> 
  3. <dependency> 
  4.   <groupId>org.apache.commons</groupId> 
  5.   <artifactId>commons-collections4</artifactId> 
  6.   <version>4.4</version> 
  7. </dependency> 

實現代碼如下:

  1. import org.apache.commons.collections4.map.LRUMap; 
  2. import org.springframework.web.bind.annotation.RequestMapping; 
  3. import org.springframework.web.bind.annotation.RestController; 
  4.  
  5. @RequestMapping("/user"
  6. @RestController 
  7. public class UserController { 
  8.  
  9.     // 最大容量 100 個,根據 LRU 算法淘汰數據的 Map 集合 
  10.     private LRUMap<String, Integer> reqCache = new LRUMap<>(100); 
  11.  
  12.     @RequestMapping("/add"
  13.     public String addUser(String id) { 
  14.         // 非空判斷(忽略)... 
  15.         synchronized (this.getClass()) { 
  16.             // 重復請求判斷 
  17.             if (reqCache.containsKey(id)) { 
  18.                 // 重復請求 
  19.                 System.out.println("請勿重復提交!!!" + id); 
  20.                 return "執行失敗"
  21.             } 
  22.             // 存儲請求 ID 
  23.             reqCache.put(id, 1); 
  24.         } 
  25.         // 業務代碼... 
  26.         System.out.println("添加用戶ID:" + id); 
  27.         return "執行成功!"
  28.     } 

使用了 LRUMap 之后,代碼顯然簡潔了很多。

5.最終版——封裝

以上都是方法級別的實現方案,然而在實際的業務中,我們可能有很多的方法都需要防重,那么接下來我們就來封裝一個公共的方法,以供所有類使用:

  1. import org.apache.commons.collections4.map.LRUMap; 
  2.  
  3. /** 
  4.  * 冪等性判斷 
  5.  */ 
  6. public class IdempotentUtils { 
  7.  
  8.     // 根據 LRU(Least Recently Used,最近最少使用)算法淘汰數據的 Map 集合,最大容量 100 個 
  9.     private static LRUMap<String, Integer> reqCache = new LRUMap<>(100); 
  10.  
  11.     /** 
  12.      * 冪等性判斷 
  13.      * @return 
  14.      */ 
  15.     public static boolean judge(String id, Object lockClass) { 
  16.         synchronized (lockClass) { 
  17.             // 重復請求判斷 
  18.             if (reqCache.containsKey(id)) { 
  19.                 // 重復請求 
  20.                 System.out.println("請勿重復提交!!!" + id); 
  21.                 return false
  22.             } 
  23.             // 非重復請求,存儲請求 ID 
  24.             reqCache.put(id, 1); 
  25.         } 
  26.         return true
  27.     } 

調用代碼如下:

  1. import com.example.idempote.util.IdempotentUtils; 
  2. import org.springframework.web.bind.annotation.RequestMapping; 
  3. import org.springframework.web.bind.annotation.RestController; 
  4.  
  5. @RequestMapping("/user"
  6. @RestController 
  7. public class UserController4 { 
  8.     @RequestMapping("/add"
  9.     public String addUser(String id) { 
  10.         // 非空判斷(忽略)... 
  11.         // -------------- 冪等性調用(開始) -------------- 
  12.         if (!IdempotentUtils.judge(id, this.getClass())) { 
  13.             return "執行失敗"
  14.         } 
  15.         // -------------- 冪等性調用(結束) -------------- 
  16.         // 業務代碼... 
  17.         System.out.println("添加用戶ID:" + id); 
  18.         return "執行成功!"
  19.     } 

小貼士:一般情況下代碼寫到這里就結束了,但想要更簡潔也是可以實現的,你可以通過自定義注解,將業務代碼寫到注解中,需要調用的方法只需要寫一行注解就可以防止數據重復提交了,老鐵們可以自行嘗試一下(需要磊哥擼一篇的,評論區留言 666)。

擴展知識——LRUMap 實現原理分析

既然 LRUMap 如此強大,我們就來看看它是如何實現的。

LRUMap 的本質是持有頭結點的環回雙鏈表結構,它的存儲結構如下:

  1. AbstractLinkedMap.LinkEntry entry; 

當調用查詢方法時,會將使用的元素放在雙鏈表 header 的前一個位置,源碼如下:

  1. public V get(Object key, boolean updateToMRU) { 
  2.     LinkEntry<K, V> entry = this.getEntry(key); 
  3.     if (entry == null) { 
  4.         return null
  5.     } else { 
  6.         if (updateToMRU) { 
  7.             this.moveToMRU(entry); 
  8.         } 
  9.  
  10.         return entry.getValue(); 
  11.     } 
  12. protected void moveToMRU(LinkEntry<K, V> entry) { 
  13.     if (entry.after != this.header) { 
  14.         ++this.modCount; 
  15.         if (entry.before == null) { 
  16.             throw new IllegalStateException("Entry.before is null. This should not occur if your keys are immutable, and you have used synchronization properly."); 
  17.         } 
  18.  
  19.         entry.before.after = entry.after
  20.         entry.after.before = entry.before; 
  21.         entry.after = this.header; 
  22.         entry.before = this.header.before; 
  23.         this.header.before.after = entry; 
  24.         this.header.before = entry; 
  25.     } else if (entry == this.header) { 
  26.         throw new IllegalStateException("Can't move header to MRU This should not occur if your keys are immutable, and you have used synchronization properly."); 
  27.     } 
  28.  

如果新增元素時,容量滿了就會移除 header 的后一個元素,添加源碼如下:

  1. protected void addMapping(int hashIndex, int hashCode, K key, V value) { 
  2.     // 判斷容器是否已滿  
  3.     if (this.isFull()) { 
  4.         LinkEntry<K, V> reuse = this.header.after
  5.         boolean removeLRUEntry = false
  6.         if (!this.scanUntilRemovable) { 
  7.             removeLRUEntry = this.removeLRU(reuse); 
  8.         } else { 
  9.             while(reuse != this.header && reuse != null) { 
  10.                 if (this.removeLRU(reuse)) { 
  11.                     removeLRUEntry = true
  12.                     break; 
  13.                 } 
  14.                 reuse = reuse.after
  15.             } 
  16.             if (reuse == null) { 
  17.                 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."); 
  18.             } 
  19.         } 
  20.         if (removeLRUEntry) { 
  21.             if (reuse == null) { 
  22.                 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."); 
  23.             } 
  24.             this.reuseMapping(reuse, hashIndex, hashCode, key, value); 
  25.         } else { 
  26.             super.addMapping(hashIndex, hashCode, key, value); 
  27.         } 
  28.     } else { 
  29.         super.addMapping(hashIndex, hashCode, key, value); 
  30.     } 

判斷容量的源碼:

  1. public boolean isFull() { 
  2.   return size >= maxSize; 

容量未滿就直接添加數據:

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

如果容量滿了,就調用 reuseMapping 方法使用 LRU 算法對數據進行清除。

綜合來說:LRUMap 的本質是持有頭結點的環回雙鏈表結構,當使用元素時,就將該元素放在雙鏈表 header 的前一個位置,在新增元素時,如果容量滿了就會移除 header的后一個元素。

總結本文講了防止數據重復提交的 6 種方法,首先是前端的攔截,通過隱藏和設置按鈕的不可用來屏蔽正常操作下的重復提交。但為了避免非正常渠道的重復提交,我們又實現了 5 個版本的后端攔截:HashMap 版、固定數組版、雙重檢測鎖的數組版、LRUMap 版和 LRUMap 的封裝版。

原文鏈接:https://mp.weixin.qq.com/s/p1MRZpnxohnX2jIpZDczmQ

 

責任編輯:武曉燕 來源: Java中文社群
相關推薦

2022-05-25 09:55:40

數據重復提交Java

2013-11-13 11:01:14

表單表單重復提交表單策略

2013-11-13 14:39:53

表單提交開發

2022-11-11 07:34:43

2022-11-15 07:39:48

2022-11-17 07:43:13

2020-11-16 09:15:07

MYSQL

2018-12-20 10:54:49

網絡攻擊網絡安全漏洞

2011-05-23 09:32:43

2010-11-23 16:56:04

mysql表單

2014-03-27 14:44:58

數據丟失防護DLP數據保護

2014-04-01 11:13:32

數據丟失

2022-07-28 16:34:16

勒索軟件惡意軟件

2024-09-02 11:05:49

2019-08-04 21:15:42

2020-10-28 09:45:02

安全數據泄露網絡

2013-01-15 10:41:50

2013-10-21 14:26:04

2009-06-05 10:37:52

struts2 國際化表單

2024-10-16 18:09:54

點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 亚洲高清在线观看 | 国产一区二区三区免费 | 日韩在线观看一区二区三区 | av网站免费在线观看 | 久草免费在线视频 | 在线视频 亚洲 | 日韩精品一区二区三区在线观看 | 欧美黄色精品 | 国产一区| 亚洲二区在线观看 | 国产成人精品一区二区三区视频 | 国产农村妇女毛片精品久久麻豆 | 日韩精品中文字幕在线 | 久久精品视频网站 | 亚欧精品一区 | 国产精品色综合 | h视频免费观看 | 99欧美精品 | 欧美一区二区三区免费电影 | 一区二区三区av | 久久亚洲一区 | 久久国产日韩 | 久久久爽爽爽美女图片 | 激情91| 国产精品视频区 | 国产精品69毛片高清亚洲 | 性欧美精品一区二区三区在线播放 | 久久91| 国产粉嫩尤物极品99综合精品 | 国产综合一区二区 | 久久精品久久久 | 最新国产精品视频 | 日韩欧美国产精品 | 在线免费观看视频黄 | 国产高清视频在线观看 | 国产乱码精品一区二区三区五月婷 | 国产精品视频入口 | 美女视频黄色片 | 玖玖在线精品 | 99riav国产一区二区三区 | 欧美日韩一二区 |