驱逐具有动态TTL周期的缓存

驱逐具有动态TTL周期的缓存

本文介绍了Spring Boot-驱逐具有动态TTL周期的缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的微服务(SERVICE-A)中,我打了一个REST API调用,以调用另一个微服务(SERVICE-B)进行登录并获取访问令牌,并且该API将以该令牌的TTL进行响应.我需要将令牌缓存到SERVICE-B响应的TTL(秒).所以我的实现如下,

From my microservice(SERVICE-A) I hit a rest api call to another microservice(SERVICE-B) for login and getting a access token and that API will respond with TTL of that token.I need to cache the token till that TTL(seconds) that is responded by SERVICE-B. So my implementation is as below,

@Cacheable("USERTOKEN")
public String getUserToken()
{
  //Hits Service-B
  //Gets token and TTL as a response from Service-B
  //Returns Token or Token with TTL
}

我需要将上述方法更改为

I need to change the above method something as

@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()返回后,也可以为"USERTOKEN"设置setExpiryTime,使用getUserToken()返回的TTL进行缓存,就可以了.我们可以将排定设置为驱逐,但这将是一个静态时间段.但是在这里,我需要根据Service-B的响应将其设置为动态值.我该如何做到这一点.

Even after returning from getUserToken() if it is possible to setExpiryTime for the "USERTOKEN" cache using the TTL returned by getUserToken() it will be fine. We can set Scheduled for eviction but it is going to be a static time period. But here I need it to be set as dynamic value based on the response from Service-B. How can I achieve this.

推荐答案

如果您使用咖啡因缓存,您可以使用不同的到期政策:

If you use caffeine cache, you can use varying expiration policy:

来自咖啡因Wiki页面:

// 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));

这篇关于Spring Boot-驱逐具有动态TTL周期的缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 18:52