从我的微服务(SERVICE-A)中,我对另一个微服务(SERVICE-B)进行了其余 api 调用以进行登录并获取访问令牌,该 API 将使用该令牌的 TTL 进行响应。
我需要缓存令牌,直到 SERVICE-B 响应的 TTL(秒)为止。所以我的实现如下,
@Cacheable("USERTOKEN")
public String getUserToken()
{
//Hits Service-B
//Gets token and TTL as a response from Service-B
//Returns Token or Token with TTL
}
我需要将上面的方法更改为
@Cacheable("USERTOKEN")
public String getUserToken()
{
//Hits Service-B
//Gets token and TTL as a response from Service-B
//Sets expiry time for "USERTOKEN" cache <-- this needs to be added
//Returns Token or Token with TTL
}
即使从 getUserToken() 返回后,如果可以使用 getUserToken() 返回的 TTL 为“USERTOKEN”缓存设置 ExpiryTime,那就没问题了。我们可以设置“计划驱逐”,但这将是一个静态时间段。但这里我需要根据 Service-B 的响应将其设置为动态值。我怎样才能做到这一点。
如果你使用咖啡因缓存,您可以使用不同的过期策略:
From 咖啡因维基页面:
// Evict based on a varying expiration policy
LoadingCache<Key, Graph> graphs = Caffeine.newBuilder()
.expireAfter(new Expiry<Key, Graph>() {
public long expireAfterCreate(Key key, Graph graph, long currentTime) {
// Use wall clock time, rather than nanotime, if from an external resource
long seconds = graph.creationDate().plusHours(5)
.minus(System.currentTimeMillis(), MILLIS)
.toEpochSecond();
return TimeUnit.SECONDS.toNanos(seconds);
}
public long expireAfterUpdate(Key key, Graph graph,
long currentTime, long currentDuration) {
return currentDuration;
}
public long expireAfterRead(Key key, Graph graph,
long currentTime, long currentDuration) {
return currentDuration;
}
})
.build(key -> createExpensiveGraph(key));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)