Guava Cache 应用场景
服务需要存储服务本地内存,但是又需要过期时间的,可以使用Guava Cache。
添加依赖包
// https://mvnrepository.com/artifact/com.google.guava/guava
compile group: 'com.google.guava', name: 'guava', version: '23.0'
编写测试类
package com.cloud.gold.test;
import java.util.concurrent.TimeUnit;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
/**
* Guava Cache 测试
*
* @bk https://home.cnblogs.com/u/huanuan/
* @简书 https://www.jianshu.com/u/d29cc7d7ca49
* @Author 六月星辰 2020年3月27日
*/
public class GuavaTest {
public static void main(String[] args) {
// 存储内存数据 时效3秒
Cache<String, String> build = CacheBuilder.newBuilder().expireAfterWrite(3, TimeUnit.SECONDS).build();
build.put("xiaozhu", "xiaozhu");
// 第一次拿内存数据
String ifPresent = build.getIfPresent("xiaozhu");
System.err.println("ifPresent = " + ifPresent);
try {
// 线程睡眠4s
TimeUnit.SECONDS.sleep(4);
} catch (Exception e) {
e.printStackTrace();
}
// 第二次拿内存数据
String ifPresent2 = build.getIfPresent("xiaozhu");
System.err.println("ifPresent2 = " + ifPresent2);
}
}
运行结果:
结果总结:
1.创建3秒的内存时效存储
2.内存存储key:‘xiaozhu’ value:'xiaozhu'
3.第一次打印成功
4.线程睡眠4s
5.打印失败(内存数据已经时效,被销毁)