一、使用场景
- 最近在项目中使用Ehcache作为jvm级别的缓存加快请求的响应速度。但是Ehcache需要在使用的时候才会去加载数据。这样在第一次请求的时候数据还是会打到数据库。基于此需要实现一个基于Ehcache的缓存预热的功能。
二、实现代码
@Slf4j
@Data
public class PoliciesCacheLoader implements BootstrapCacheLoader {
private boolean asynchronous;
private RangerPolicyApiService policyApiService;
public PoliciesCacheLoader(boolean asynchronous,RangerPolicyApiService policyApiService){
this.asynchronous = asynchronous;
this.policyApiService = policyApiService;
}
@Override
public void load(Ehcache cache) throws CacheException {
if (asynchronous) {
BootstrapThread thread = new BootstrapThread(cache);
thread.start();
} else {
doLoad(cache);
}
}
@Override
public boolean isAsynchronous() {
return this.asynchronous;
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
private void doLoad(Ehcache cache){
Map<String,Object> map