我有一个多模块项目,所有模块在他们自己的ehcache.xml中定义他们的缓存配置。这个用例是由现在没有维护的"ehcache-spring-annotations"项目通过如下配置来解决的:
<ehcache:annotation-driven cache-manager="ehCacheManager" create-missing-caches="true"/>
<bean id="ehCacheManager" class="net.sf.itcb.addons.cachemanager.ItcbEhCacheManagerFactoryBean">
<property name="configLocations" value="classpath*:ehcache.xml"/>
<property name="shared" value="true"/>
</bean>
我在Spring的缓存抽象中尝试了类似的东西。
<cache:annotation-driven/>
<bean id="cacheManager"
class="org.springframework.cache.ehcache.EhCacheCacheManager"
p:cache-manager-ref="ehcache"/>
<bean id="ehcache"
class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
p:config-location="classpath*:ehcache.xml"/>
然而,我遇到了这个异常:
Caused by: java.io.FileNotFoundException:
class path resource [classpath*:ehcache.xml] cannot be opened because
it does not exist
有人能解释一下在多模块项目中配置Spring的EhCache缓存抽象的正确方法是什么吗?
如果您希望在单个Spring上下文中有多个CacheManagers
,则必须定义多个bean并向它们添加限定符,以便能够根据某些上下文区分它们。
所以这里没有什么特定的缓存,它是Spring中相同类型的经典多个bean。
最后,我们放弃了ehcache.xml,开始使用基于Java的缓存配置,这就解决了这个问题。
通过以不同的方式创建缓存管理器来实现这一点,因为spring不允许在上下文中使用两个EhCacheManagerFactoryBean,并且在bean创建后很快设置了配置位置,因此无法更新。
@Bean("ehCacheManager1")
fun EhCacheCacheManager ehCacheCacheManager1(ehCacheManagerFactoryBean: CacheManager): EhCacheCacheManager =
EhCacheCacheManager(ehCacheManagerFactoryBean)
@Bean("ehCacheManagerFactoryBean")
public EhCacheManagerFactoryBean ehCacheManagerFactoryBean() {
EhCacheManagerFactoryBean cacheManagerFactoryBean = new EhCacheManagerFactoryBean();
cacheManagerFactoryBean.setConfigLocation(new ClassPathResource("ehcache1.xml"));
cacheManagerFactoryBean.setShared(true);
return cacheManagerFactoryBean;
}
@Bean("ehCacheManager2")
@Primary
fun ehCacheManager2(): EhCacheCacheManager {
val configLocation = cacheProperties().resolveConfigLocation(ClassPathResource("ehcache.xml"))
return EhCacheCacheManager(CacheManager.create(configLocation.url))
}
@Bean
fun cacheProperties() = CacheProperties()