Spring Cache整合Ehcache根据Ehcache配置设置生效的缓存项
最近项目需要使用spring cache整合ehcache来实现(只有很少的数据需要缓存,不想增加项目部署难度),但是整合后发现报Cannot find cache named 异常,发现是引入的一个第三方jar包也在使用spring cache。所以能不能根据项目ehcache.xml配置的具体缓存项来实现选择哪些cache是生效的呢。
在springboot整合缓存时,我们可以实现CachingConfigurerSupport 来细化缓存配置,而其中cacheResolver方法返回的CacheResolver接口实现类是可以细化具体每一个缓存方法究竟使用哪个缓存的。所以我们只需要继承并重写AbstractCacheResolver中的getCacheNames方法,使之返回我们在Ehcache中已经定义了的缓存名称就可以实现缓存注解只对Ehcache配置了项起作用。
@Component public class EhCacheResolver extends AbstractCacheResolver { /** * Provide the name of the cache(s) to resolve against the current cache manager. * <p>It is acceptable to return {@code null} to indicate that no cache could * be resolved for this invocation. * * @param context the context of the particular invocation * @return the cache name(s) to resolve, or {@code null} if no cache should be resolved */ @Override protected Collection<String> getCacheNames(CacheOperationInvocationContext<?> context) { return getCacheManager().getCacheNames(); } /** * Set the {@link CacheManager} that this instance should use. * * @param cacheManager */ @Override @Autowired public void setCacheManager(CacheManager cacheManager) { super.setCacheManager(cacheManager); } }