本地缓存Guava Cache、分布式缓存Redis与数据库mysql的整合
在日常开发中,当我们数据访问非常频繁的时候可以使用缓存,以减少持久层的压力。至于本地缓存Guava Cache大家可以看我之前的博客。redis跟mysql这里不做过多论述
1、创建一个CacheUtils工具类
import com.google.common.cache.Cache;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class CacheUtils {
private static final Logger log = LoggerFactory.getLogger(CacheUtils.class);
@Autowired
private RedisUtil redisUtil;
public CacheUtils() {
}
public String getCache(Cache<String, String> cache, String key) {
if (cache == null) {
return this.redisUtil.get(key);
} else {
String localCache = (String)cache.getIfPresent(key);
if (StringUtils.isNotBlank(localCache)) {
log.debug("配置[key:{}]在本地缓存中的信息为[{}]", key, localCache);
return localCache;
} else {
localCache = this.redisUtil.get(key);
log.debug("配置[key:{}]在分布式缓存中的信息为[{}]", key, localCache);
if (StringUtils.isBlank(localCache)) {
return "";
} else {
cache.put(key, localCache);
return localCache;
}
}
}
}
public void setCache(Cache<String, String> cache, String key, String value, long time) {
if (cache != null) {
cache.put(key, value);
}
this.redisUtil.setAndTime(key, value, time);
}
}
2、本地缓存的创建
public class NoticeConstant {
// 本地缓存,存放数据量变动比较少的key
public final static Cache<String, String> localCache = CacheBuilder.newBuilder()
.maximumSize(200)
.expireAfterWrite(3, TimeUnit.MINUTES)
.build();
}
3、ServiceImpl的应用
public Response<List<BananerInfo>> bananerPage(@Valid @RequestBody BananerInfo param) {
// 优先查询缓存,缓存查询不到,则穿透到数据库
String cacheKey = "keyName";
String cacheList = cacheUtils.getCache(NoticeConstant.localCache, cacheKey);
List<BananerInfo> list = Lists.newArrayList();
if(StringUtils.isNotBlank(cacheList)){
list = JSONArray.parseArray(cacheList, BananerInfo.class);
}else{
// 穿透到数据库
list = contentService.bananerPage(param);
// 将查询的数据刷新到本地缓存以及redis
cacheUtils.setCache(NoticeConstant.localCache, cacheKey,JSONArray.toJSONString(list), -1);
}
return new Response<>(Response.OK_STATUS, "查询成功", list);
}