如何解决春季启动-驱逐具有动态TTL周期的缓存
在我的微服务(SERVICE-A)中,我打了一个REST API调用,以调用另一个微服务(SERVICE-B)进行登录并获取访问令牌,该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”高速缓存设置setExpiryTime,也可以。我们可以将排定设置为驱逐,但这将是一个静态时间段。但是在这里,我需要根据Service-B的响应将其设置为动态值。我该怎么做到。
解决方法
如果您使用caffeine cache,则可以使用不同的到期政策:
// 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,long currentTime,long currentDuration) {
return currentDuration;
}
public long expireAfterRead(Key key,long currentDuration) {
return currentDuration;
}
})
.build(key -> createExpensiveGraph(key));
,
您使用的是哪种缓存服务?
如果您使用Redis缓存,他们为此有很多命令:
EXPIRE:设置密钥超时。 EXPIREAT:与前一个相同,但是需要一个绝对的Unix时间戳(自1970年1月1日以来的秒数)。 TTL:返回具有超时的密钥的剩余生存时间 您必须了解有关Redis过期的重要一件事:仅当使用SET或GETSET移除或覆盖键时,才会清除超时值。所有其他命令(INCR,LPUSH,HMSET等)将永远不会更改初始超时。
绝对到期是使用EXPIRE的Redis的本机功能。要实现滑动到期,您只需在每个命令后将超时值重置为
。执行此操作的基本方法可能是
MULTI
GET MYKEY
EXPIRE MYKEY 60
EXEC
,
如果您正在使用Spring的默认实现,则将无法设置Cache TTL。但是,使用其他提供程序(例如EhCache,Gemfire和Guava),您只能在配置缓存管理器时执行此操作。 See ehcache Documentation和Spring's Gemfire's Documentation。对于Guava see
像这样-对于Ehcache。
CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
.with(CacheManagerBuilder.persistence(tmpDir.newFile("myData")))
.withCache("threeTieredCache",CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class,String.class,ResourcePoolsBuilder.newResourcePoolsBuilder()
.heap(10,EntryUnit.ENTRIES)
.offheap(1,MemoryUnit.MB)
.disk(20,MemoryUnit.MB,true))
.withExpiry(ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofSeconds(20)))
).build(false);
Configuration configuration = cacheManager.getRuntimeConfiguration();
XmlConfiguration xmlConfiguration = new XmlConfiguration(configuration);
String xml = xmlConfiguration.toString();
对于-Gemfire
<gfe:region-template id="BaseRegionTemplate" initial-capacity="51" load-factor="0.85" persistent="false" statistics="true"
key-constraint="java.lang.Long" value-constraint="java.lang.String">
<gfe:cache-listener>
<bean class="example.CacheListenerOne"/>
<bean class="example.CacheListenerTwo"/>
</gfe:cache-listener>
<gfe:entry-ttl timeout="600" action="DESTROY"/>
<gfe:entry-tti timeout="300 action="INVLIDATE"/>
</gfe:region-template>
对于-番石榴的咖啡因或内部实现
LoadingCache<Key,Graph> graphs = Caffeine.newBuilder()
.maximumSize(10_000)
.expireAfterWrite(5,TimeUnit.MINUTES)
.refreshAfterWrite(1,TimeUnit.MINUTES)
.build(key -> createExpensiveGraph(key));
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。