Spring Boot集成Caffeine缓存:如何获取缓存对象的添加时间?
获取Caffeine缓存条目的添加时间方案
Caffeine本身默认并没有提供直接获取缓存条目创建时间的API,不过我们可以通过包装缓存值的方式轻松实现这个需求,下面是具体的实现步骤:
1. 创建缓存值包装类
先定义一个类,用来存储原始对象和它的创建时间:
public class CachedValue<T> { private final T value; private final long createdAt; public CachedValue(T value) { this.value = value; // 记录对象存入缓存时的时间戳 this.createdAt = System.currentTimeMillis(); } // 提供getter方法 public T getValue() { return value; } public long getCreatedAt() { return createdAt; } }
2. 存入缓存时包装对象
之后往缓存中存数据的时候,把原始对象包装成CachedValue实例:
// 替换成你实际的key和原始对象 Object key = "your-cache-key"; YourObject originalObject = getYourObject(); cache.put(key, new CachedValue<>(originalObject));
3. 获取最热条目的创建时间
现在你可以在获取最热条目时,直接提取创建时间了:
private final CaffeineCache caffeineCache = (CaffeineCache) caffeineCacheManager.getCache("myCacheName"); Cache<Object, Object> cache = this.caffeineCache.getNativeCache(); // 获取最热的1个缓存条目 cache.policy().eviction().get().hottest(1).forEach(entry -> { if (entry.getValue() instanceof CachedValue<?>) { CachedValue<?> cachedValue = (CachedValue<?>) entry.getValue(); long createTimestamp = cachedValue.getCreatedAt(); // 这里可以根据需求转换为日期格式,或者直接使用时间戳 System.out.println("该条目添加到缓存的时间:" + new Date(createTimestamp)); } });
额外说明
如果你的项目是通过Spring的@Cacheable等注解来使用缓存的,不想手动包装对象的话,可以自定义CacheManager或者CacheResolver,在缓存写入时自动完成包装,读取时自动解析原始对象,这样业务代码就不需要感知包装逻辑了。不过如果是手动操作缓存的场景,上面的方案已经足够简洁易用。
内容的提问来源于stack exchange,提问作者dunnj515
相关产品推荐
相关产品推荐

