相信大家都有用过本地缓存的经历,很多时候我们用ConcurrentHashMap来作为缓存,但是ConcurrentHashMap毕竟是个Map,而不是专门的缓存,像缓存自动失效、缓存淘汰策略、缓存的加载并发问题等ConcurrentHashMap都没有提供相应的功能,需要自己改造。
下面就给大家介绍一款小而精的本地缓存Guava Cache,他是Google Guava工具包的一个模块。
<dependencies>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>24.1-android</version>
</dependency>
</dependencies>
public class MainTest {
public static void main(String[] args) throws Exception {
LoadingCache<String, String> objectCache = CacheBuilder.newBuilder()
//同时写缓存的线程数
.concurrencyLevel(8)
//写入后多久缓存失效
.expireAfterWrite(1, TimeUnit.SECONDS)
//访问后多久缓存失效
.expireAfterAccess(1, TimeUnit.SECONDS)
//设置缓存容量
.initialCapacity(10).maximumSize(100)
//设置要统计缓存的命中率
.recordStats()
//设置缓存移除监听器
.removalListener(removalNotification -> {
System.out.println(removalNotification.getKey() + " was removed, cause is :" + removalNotification.getCause());
})
.build(new CacheLoader<String, String>() {
@Override
public String load(String key) throws Exception {
System.out.println("load data:" + key);
String value = key + ":cache-value";
return value;
}
})
// .build()
;
objectCache.put("tuyou", "tuyou");
objectCache.put("yangrui", "yangrui");
System.out.println(objectCache.get("tuyou"));
Thread.sleep(2000);
System.out.println(objectCache.get("tuyou"));
objectCache.invalidate("tuyou"); //主动删除缓存
System.out.println(objectCache.get("tuyou"));
}
}