背景交代: 使用ajax來提交創建訂單,需求是不能創建重復的訂單
-
使用js限制提交的頻率
// 設置內容為可用,但是不能繼續操作 $.fn.setBtnTxtEnabled = function (func) { if (!this) { throw new Error("element 不能為空"); } this.text(this.data('text')); } // 設置按鈕不可用 $.fn.setBtnEnabled = function (func) { if (!this) { throw new Error("element 不能為空"); } this.text(this.data('text')); this.data('cando', true); //設置該屬性判斷不能提交 func && func(); //執行額外操作 } // 判斷button是否可以操作 $.fn.isBtnEnabled = function (func) { if (!this) { throw new Error("element 不能為空"); } if (this.data('cando') == undefined) { //第一次未設置返回true return true; } return this.data('cando'); //之后返回設置的值 }
-
在服務器端限制提交頻率
public static class ApiLimit { /// <summary> /// /// </summary> /// <param name="sessionname"></param> /// <param name="time">默認5秒</param> public static void Limit(string sessionname, int time = 5) { // 這個session不需要清除,3秒之后,已經跳轉到其他其他頁面,然后用戶3s之后,這個session的檢驗就已經失效了 if (HttpContext.Current.Session[sessionname] != null && (HttpContext.Current.Session[sessionname].SafeToLong() > DateTime.Now.Ticks)) { throw new Exception("提交太頻繁,請稍后重試"); } else { HttpContext.Current.Session[sessionname] = DateTime.Now.AddSeconds(time).Ticks; ; } } }
-
在提交order的時候做判斷
3.1. 判斷orderid是否存在,存在則不添加 3.2. 獲取用戶最后一條訂單記錄,可以按業務需求限制兩條記錄的時間間隔必須大於多少,否則忽略
基本上這樣就可以保證在並發時,防止重復訂單的出現,但是效率應該是不高的