guava缓存的简单使用

创建工具类:

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;


@Component
public class BaseCache {

private Cache<String,Object> cache = CacheBuilder.newBuilder()
//初始大小
.initialCapacity(10)
//最大值
.maximumSize(100)
//并发数
.concurrencyLevel(5)
//缓存过期时间
.expireAfterWrite(600, TimeUnit.SECONDS)
//缓存命中率
.recordStats()
.build();

public Cache<String, Object> getCache() {
return cache;
}

public void setCache(Cache<String, Object> cache) {
this.cache = cache;
}
}

key的管理类:

/**
* 缓存key管理类
*/
public class CacheKeyManager {
/**
* 首页轮播图
*/
public static final String 常量名 = "xxx:xxxx:xxx";//中间用:隔开
public static final String 常量名 = "xxx:xxx:xxx";
}
简单使用:
try{

Object cacheObj = baseCache.getCache().get(CacheKeyManager.常量名, ()->{

//调用mapper中的方法
System.out.println("从数据库中取数据");
return //mapper中方法返回类型;
});

if (cacheObj instanceof List){//返回类型是否为列表
列表类型 名称= (强转返回列表)cacheObj;

return 名称;
    }
}catch (Exception e){
e.printStackTrace();
}
return null;



posted @ 2021-12-05 11:00  智慧搬运工  阅读(292)  评论(0)    收藏  举报