下面給大家介紹springboot整合ehcache 實現支付超時限制的方法,具體內容如下所示:
1
2
3
4
5
|
<dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-core</artifactId> <version> 2.6 . 11 </version> </dependency> |
pom文件中引入ehcache依賴
在類路徑下存放ehcache.xml文件。
application.xml中指定:
1
2
3
4
|
spring: cache: jcache: config: classpath:ehcache.xml |
類標注@EnableCaching
實現核心代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
/* * 記錄用戶支付的時間戳 */ public void pinUser(Object userKey) throws Exception{ Cache cache = manager.getCache(cacheName); Element element = cache.get(userKey); if(element == null){ /*如果沒有找到用戶的支付記錄,則記錄緩存,然后繼續*/ Element newE = new Element(userKey, new Date().getTime()); cache.put(newE); } else { /*如果存在用戶的支付記錄,則應該拋出異常,并提示用戶相應的信息*/ long inTime = (Long) element.getObjectValue(); long timeToWait = (getTimeToLive() - (new Date().getTime() - inTime)/1000); //提示需要等待的時間 throw new Exception(String.format("還需等待%s秒",String.valueOf(timeToWait))); } } /* * 刪除用戶支付的時間戳(該方法用于系統內部支付失敗時,手動去掉用戶的支付記錄,從而不影響用戶再次嘗試) * 正常時候不應該調用該方法,而是應該等緩存超時后自動清除 */ public void unPinUser(Object userKey) { Cache cache = manager.getCache(cacheName); cache.remove(userKey); } /* * 獲取緩存配置,用來換算用戶還需等待的時間,從而給出較為友好的等待時間提示。 */ private long getTimeToLive(){ Cache cache = manager.getCache(cacheName); return cache.getCacheConfiguration().getTimeToLiveSeconds(); } |
使用
在調用支付接口的地方調用PayToken.getInstance().pinUser(user.getKey())
即可,若拋出異常,即說明支付間隔時間太小,同時如果還有附加數據操作,拋出異常亦可以觸發回滾操作。
若是系統原因導致執行失敗而仍需用戶等待是不合理的,因此增加了解除用戶記錄的方法PayToken.getInstance().unPinUser(user.getKey())
。
總結
以上所述是小編給大家介紹的springboot整合ehcache 實現支付超時限制的方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:https://www.cnblogs.com/kiwi0506/articles/7135150.html