maven依赖
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>28.1-jre</version>
</dependency>
应用
首先定义这个Cache。
public class GlobalCache {
private static GlobalCache defaultInstance = new GlobalCache();
public static GlobalCache getDefaultInstance() {
return defaultInstance;
}
// 因为Guava Cache支持定时回收,所以设置5分钟就清空缓存
private Cache<String, Object> cache = CacheBuilder.newBuilder().expireAfterWrite(5, TimeUnit.MINUTES).build();
public Object get(String key, Callable<Object> callable) throws Exception {
return cache.get(key, callable);
}
public <T> T get(String key) throws Exception {
return (T) cache.getIfPresent(key);
}
public void put(String key, Object value) throws Exception {
cache.put(key, value);
}
}
使用方法如下:
Bean cache = GlobalCache.getDefaultInstance().get(key);
if (dispatchRule == null) {
cache = objectMapper.selectById(id);
GlobalCache.getDefaultInstance().put(key, cache);
}
缓存回收
一个残酷的现实是,我们几乎一定没有足够的内存缓存所有数据。所以必须决定:什么时候某个缓存项就不值得保留了?Guava Cache提供了三种基本的缓存回收方式:
- 基于容量回收
- 定时回收
- 基于引用回收。
本文深入探讨Guava Cache的实现原理与应用实践,包括基于容量、定时及引用的回收策略,通过具体代码示例展示如何配置和使用Guava Cache进行高效的数据缓存。
1261

被折叠的 条评论
为什么被折叠?



