导入pom文件
<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>27.0.1-jre</version>
</dependency>
测试demo
public class Test01 {
private static Cache<String, String> loadingCache = CacheBuilder.newBuilder()
/*设置缓存容器的初始容量大小为10*/
.initialCapacity(10)
/*设置缓存容器的最大容量大小为100*/
.maximumSize(100)
/*设置记录缓存命中率*/
.recordStats()
/*设置并发级别为8,智并发基本值可以同事些缓存的线程数*/
.concurrencyLevel(8)
/*设置过期时间为2秒*/
.expireAfterAccess(2, TimeUnit.SECONDS).build();
public static void setKeyVal(String key, String value){
loadingCache.put(key, value);
}
public static String getValByKey(String key){
String value = loadingCache.getIfPresent(key);
return value;
}
public static void delKey(String key){
loadingCache.invalidate(key);
}
public static void main(String[] args) throws Exception {
Test01 test01 = new Test01();
test01.setKeyVal("hello","world");
Thread.sleep(3000l);
String str = test01.getValByKey("hello");
System.out.println(str);
}
}