将对象添加到Caffeine缓存时

时间:2018-03-29 21:13:56

标签: spring spring-boot

我在项目中使用Spring Boot缓存并使用Caffiene。我已经为项目添加了一些Caffeine的默认配置,我可以使用以下代码从缓存中获取最新的对象:

private final CaffeineCache caffeineCache = (CaffeineCache) caffeineCacheManager.getCache("myCacheName");
Cache<Object, Object> cache = this.caffeineCache.getNativeCache();
cache.policy().eviction().get().hottest(1);

我实际上并不想要对象本身,但我想知道它何时被添加到缓存中。有没有办法找出这个对象何时被添加到缓存中?

1 个答案:

答案 0 :(得分:0)

感谢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;