springboot整合ehcache 实现支付超时限制的方法

2025-05-27 0 70

下面给大家介绍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 实现支付超时限制的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对快网idc网站的支持!

原文链接:https://www.cnblogs.com/kiwi0506/articles/7135150.html

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 springboot整合ehcache 实现支付超时限制的方法 https://www.kuaiidc.com/76336.html

相关文章

发表评论
暂无评论