代码示例如下:
/**
* 本地内存
*/
LoadingCache<Long,String> cache = CacheBuilder.newBuilder().
//30min过期
expireAfterWrite(30, TimeUnit.MINUTES).
//最大保存10个值
maximumSize(10).
build(new CacheLoader<Long, String>() {
//不存在时缓存这个值
@Override
public String load(Long s) throws Exception {
return one(s);
}
});
@Override
public List<String> getAllCache(List<Long> idList) {
List<String> cacheResult = new ArrayList<>();
for(Long id:idList){
String value = cache.getUnchecked(id);
cacheResult.add(value);
}
return cacheResult;
}
/**
* 模拟调用
* @param id
* @return
*/
private String one(Long id){
log.info("调用one");
try {
//模拟查询DB耗时
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "test_"+id;
}