說到這裏,不得不由衷的佩服spring boot確實不錯,以前我還要基於spring cache 把guava cache和redis裝進去,現在基於spring boot的 autoconfigure的cache封裝,就可以很方便把這些用起來,關於 springboot的cache使用,請參見:http://www.jianshu.com/p/64f684bd0ce9 但麻煩的地方在於,我們的框架+代碼自動生成,在整個體系裏,默認的實現都在abstract抽象類,那麼它只能做一次cacheNames的配置, 如果設置 cacheEvict(allEntries=true),會做全局的失效,而正常是這個模型內的緩存失效,好在 可以自定義 CacheResolver。
不過自定義的CacheResolver,需要注入cacheManager, 而cacheManager不能注入成功, 最終 使用 @Lazy,懶加載,並且 在spring boot應用啓動時 將ApplicationContext 設置給ApplicationContextHolder,在 需要的時候獲取到cachemanager設置給CacheResolver, 具體代碼:
@Component("runtimeImplCacheResolver")
@Lazy
public classRuntimeImplCacheResolverextendsAbstractCacheResolver {
privateApplicationContextctx;
publicRuntimeImplCacheResolver() {
//super.setCacheManager(SpringContextHolder.getApplicationContext().getBean(CacheManager.class));
}
@PostConstruct
public voidinit(){
super.setCacheManager(SpringContextHolder.getApplicationContext().getBean(CacheManager.class));
}
@Override
protectedCollection getCacheNames(CacheOperationInvocationContext context) {
if(context.getOperation().getCacheNames().contains("SECOMMONDYN")){
Set cacheName =newHashSet();
context.getTarget().getClass().toString();
String simpleName = context.getTarget().getClass().getSimpleName();
simpleName = simpleName.substring(0, simpleName.length() -11);
cacheName.add(simpleName);
returncacheName;
}else{
returncontext.getOperation().getCacheNames();
}
}
}
框架調用:
@CacheConfig(cacheNames ="SECOMMONDYN", cacheResolver ="runtimeImplCacheResolver")