我在一个项目中使用Spring Boot缓存,并使用Caffiene。我已经在项目中添加了一些咖啡因的默认配置,我可以使用以下代码从缓存中获取最新的对象:
private final CaffeineCache caffeineCache = (CaffeineCache) caffeineCacheManager.getCache("myCacheName");
Cache<Object, Object> cache = this.caffeineCache.getNativeCache();
cache.policy().eviction().get().hottest(1);我实际上并不想要对象本身,但我想知道它是什么时候添加到缓存中的。有没有办法知道这个对象是什么时候被添加到缓存中的?
发布于 2018-04-03 23:45:09
感谢Ben Maines的评论,我找到了我的问题的解决方案。我使用过期时间戳计算了缓存时间:
CacheResponse cacheResponse = new CacheResponse();
Cache<Object, Object> cache = this.caffeineCache.getNativeCache();
if(cache.policy().eviction().get().hottest(1).keySet().iterator().hasNext()) {
// Time in milliseconds since object was cached
OptionalLong time = cache.policy().expireAfterWrite().get().ageOf(cache.policy().eviction().get().hottest(1).keySet().iterator().next(), TimeUnit.MILLISECONDS);
LOGGER.info("Calculating last UTC cached date");
// Calculate last cached time and set the object in the cache response
cacheResponse.setTime(Instant.now().minusMillis(time.getAsLong()).atZone(ZoneOffset.UTC).toLocalDateTime());
} else {
LOGGER.info("Cache appears to be empty.");
}
cacheResponse.setNumCachedItems(cache.estimatedSize());
return cacheResponse;https://stackoverflow.com/questions/49565135
复制相似问题