其他分享
首页 > 其他分享> > 查询带参接口引入本地缓存

查询带参接口引入本地缓存

作者:互联网

try{
String videoCacheKey = String.format(CacheKeyManager.VIDEO_DETAIL,videoId);

Object cacheObj = baseCache.getOneHourCache().get( videoCacheKey ,()->{
Video video = videoMapper.findDetailById(videoId);
return video;
});
if (cacheObj instanceof Video){
Video video = (Video)cacheObj;
return video;
}
}catch (Exception e){
e.printStackTrace();
}
return null;


管理类
/**
* 缓存key管理类
*/
public class CacheKeyManager {
/**
* 首页轮播图
*/
public static final String INDEX_BANNER_KEY = "index:banner:list";
public static final String INDEX_VIDEO_LIST = "index:video:list";

/**
* 带参加 %s
*/
public static final String VIDEO_DETAIL = "video:detail:%s";
}

工具类

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();

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

public Cache<String, Object> getOneHourCache() {
return oneHourCache;
}

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

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

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

标签:cache,return,Cache,接口,带参,缓存,video,public
来源: https://www.cnblogs.com/xmcode/p/15644971.html