springboot incorporates ehcache's approach to payment timeout limits
- 2020-12-26 05:44:39
- OfStack
springboot integrates ehcache to realize payment timeout limitation, as shown below:
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.6.11</version>
</dependency>
ehcache dependencies are introduced in the pom file
Store the ehcache.xml file under the classpath.
application.xml specifies:
spring:
cache:
jcache:
config: classpath:ehcache.xml
Class mark @ EnableCaching
Implement the core code
/*
* Record the timestamp of the user's payment
*/
public void pinUser(Object userKey) throws Exception{
Cache cache = manager.getCache(cacheName);
Element element = cache.get(userKey);
if(element == null){
/* If the user's payment record is not found, the record is cached and continues */
Element newE = new Element(userKey, new Date().getTime());
cache.put(newE);
} else {
/* If a user's payment record exists, an exception should be thrown and the user should be prompted for the appropriate information */
long inTime = (Long) element.getObjectValue();
long timeToWait = (getTimeToLive() - (new Date().getTime() - inTime)/1000);
// Indicate how long you need to wait
throw new Exception(String.format(" Still need to wait for %s seconds ",String.valueOf(timeToWait)));
}
}
/*
* Delete the timestamp of the user's payment (this method is used to manually delete the user's payment record when the payment fails within the system, so as not to affect the user to try again)
* This method should not normally be called, but should be cleared automatically after the cache has timed out
*/
public void unPinUser(Object userKey) {
Cache cache = manager.getCache(cacheName);
cache.remove(userKey);
}
/*
* Gets the cache configuration, which is used to calculate the amount of time the user still has to wait, thus giving a friendlier wait time hint.
*/
private long getTimeToLive(){
Cache cache = manager.getCache(cacheName);
return cache.getCacheConfiguration().getTimeToLiveSeconds();
}
use
Call where the payment interface is called
PayToken.getInstance().pinUser(user.getKey())
If an exception is thrown, the payment interval is too small, and if there is an additional data operation, the thrown exception can trigger a rollback operation.
It is not reasonable to have the user wait if the execution fails for a system reason, so the method of undoing the user record has been added
PayToken.getInstance().unPinUser(user.getKey())
.
conclusion