当前位置: 移动技术网 > IT编程>开发语言>Java > springboot整合ehcache 实现支付超时限制的方法

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

2019年07月19日  | 移动技术网IT编程  | 我要评论

久播电影网,海上钢琴师qvod,利川市政府

下面给大家介绍springboot整合ehcache 实现支付超时限制的方法,具体内容如下所示:

<dependency>
 <groupid>net.sf.ehcache</groupid>
 <artifactid>ehcache-core</artifactid>
 <version>2.6.11</version>
</dependency>

pom文件中引入ehcache依赖   

在类路径下存放ehcache.xml文件。

application.xml中指定:

spring:
 cache:
 jcache:
  config: classpath:ehcache.xml

类标注@enablecaching

实现核心代码

/*
 * 记录用户支付的时间戳
 */
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 实现支付超时限制的方法,希望对大家有所帮助

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网