Google的CacheBuilder
详细api参考:https://blog.youkuaiyun.com/luzhensmart/article/details/92635779
1. util
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import java.util.concurrent.TimeUnit;
/**
* 缓存默认5min
*/
public class CacheUtil {
//CacheBuilder的构造函数是私有的,只能通过其静态方法newBuilder()来获得CacheBuilder的实例
private static final LoadingCache<String, Object> cache = CacheBuilder.newBuilder()
//设置并发级别为8,并发级别是指可以同时写缓存的线程数
.concurrencyLevel(8)
//设置写缓存后5分钟过期
.expireAfterWrite(5, TimeUnit.MINUTES)
//设置缓存容器的初始容量为10
.initialCapacity(10)
//设置缓存最大容量为100,超过100之后就会按照LRU最近虽少使用算法来移除缓存项
.maximumSize(1000)
//设置要统计缓存的命中率
.recordStats()
//build方法中可以指定CacheLoader,在缓存不存在时通过CacheLoader的实现自动加载缓存
.build(
new CacheLoader<String, Object>() {
@Override
public Object load(String key) throws Exception {
return null;
}
}
);
public static synchronized void put(String key, Object object) {
cache.put(key, object);
}
public static synchronized Object get(String key) {
// 不存在返回null
return cache.getIfPresent(key);
}
public static void main(String[] args) throws Exception {
//缓存接口这里是LoadingCache,LoadingCache在缓存项不存在时可以自动加载缓存
LoadingCache<String, Object> cache
//CacheBuilder的构造函数是私有的,只能通过其静态方法newBuilder()来获得CacheBuilder的实例
= CacheBuilder.newBuilder()
//设置并发级别为8,并发级别是指可以同时写缓存的线程数
.concurrencyLevel(8)
//设置写缓存后5分钟过期
.expireAfterWrite(5, TimeUnit.SECONDS)
//设置缓存容器的初始容量为10
.initialCapacity(10)
//设置缓存最大容量为100,超过100之后就会按照LRU最近虽少使用算法来移除缓存项
.maximumSize(1000)
//设置要统计缓存的命中率
.recordStats()
//build方法中可以指定CacheLoader,在缓存不存在时通过CacheLoader的实现自动加载缓存
.build(
new CacheLoader<String, Object>() {
@Override
public Object load(String key) throws Exception {
return null;
}
}
);
cache.put("1", 1);
System.out.println(Integer.MIN_VALUE);
while (true) {
System.out.println(cache.getIfPresent("1"));
Thread.sleep(1000L);
}
}
}