Guava Cache
一、引入Maven配置pom
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>20.0</version> </dependency>
二、新建一个cache类
private static LoadingCache< String, String> loadingCache = CacheBuilder.newBuilder() // 设置并发级别为8 ,并发级别是指可以同时写缓存的线程数 .concurrencyLevel(8) // 设置写缓存后8秒过期 .expireAfterWrite(8, TimeUnit.SECONDS) // 缓存容器的初始容量 .initialCapacity(100) // 缓存容器的最大容量,超过则会安装LRU算法,删除最近使用最少的数据 .maximumSize(1000) // 设置要统计缓存命中率 .recordStats() // 设置缓存的移除通知 .removalListener(new RemovalListener<Object, Object>() { @Override public void onRemoval(RemovalNotification<Object, Object> removalNotification) { log.debug(" LoadingCache Remove Cahe key{} , value:{} .",removalNotification.getKey(),removalNotification.getValue()); } }) // /build方法中可以指定CacheLoader,在缓存不存在时通过CacheLoader的实现自动加载缓存 .build(new CacheLoader<String, String>() { @Override public String load(String key) throws Exception { log.debug(" LoadingCache getKey is Null Cahe key is {}.",key); return "null"; } });
三、写一个测试main方法如下:
public static void main(String[] args) throws ExecutionException, InterruptedException { loadingCache.put("wanghao","wanghao"); log.debug("wanghao"); log.error("wanghaoerror"); int i = 1; while (true){ System.out.println(loadingCache.get("wanghao") + " "+ i ); Thread.sleep(1000); i++; }
往缓存里面存储一个key和value,然后进行循环获取。每次暂停1秒,打印结果如下:

可以看到我设置了8秒失效,打印了八次后,打印remove key的日志与获取key为空的日志。
可以使用
System.out.println(loadingCache.stats().toString());
打印缓存命中信息

浙公网安备 33010602011771号