首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将对象添加到Caffeine缓存时

将对象添加到Caffeine缓存时
EN

Stack Overflow用户
提问于 2018-03-30 05:13:56
回答 1查看 590关注 0票数 0

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

代码语言:javascript
复制
private final CaffeineCache caffeineCache = (CaffeineCache) caffeineCacheManager.getCache("myCacheName");
Cache<Object, Object> cache = this.caffeineCache.getNativeCache();
cache.policy().eviction().get().hottest(1);

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

EN

回答 1

Stack Overflow用户

发布于 2018-04-03 23:45:09

感谢Ben Maines的评论,我找到了我的问题的解决方案。我使用过期时间戳计算了缓存时间:

代码语言:javascript
复制
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;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49565135

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档