java使用Guava cache做内存缓存
物料准备:
1.pom引入guava依赖
2.定义一个公用的工具类
3.在代码中通过工具类使用Guava cache
引入guava依赖
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>28.2-jre</version>
</dependency>
定义工具类GuavaCacheUtil.java
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import java.util.concurrent.TimeUnit;
public class GuavaCacheUtil {
/**
* 使用guava需要引入依赖
* <dependency>
* <groupId>com.google.guava</groupId>
* <artifactId>guava</artifactId>
* <version>28.2-jre</version>
* </dependency>
*/
private static Cache<String, Object> cache = CacheBuilder.newBuilder()
//5分钟后过期
.expireAfterWrite(5, TimeUnit.MINUTES)
//最大10个缓存
.maximumSize(10)
.build();
public static Object getCache(String k) {
return cache.getIfPresent(k);
}
public static void putCache(String k, Object value) {
cache.put(k, value);
}
}
在代码中使用guava cache
往guava cache里存放KV缓存数据
GuavaCacheUtil.putCache("licValid",validLicResult);
从guava cache里读取KV缓存数据
ValidateResult validLicResult = (ValidateResult)GuavaCacheUtil.getCache("licValid");