我使用的是Spring启动(1.4.2.RELEASE)和Ehcache(2.4.3)
缓存正在开发环境中使用,但它没有在其他环境中使用(命中)(测试和产品) .
代码如下:
pom.xml
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
在 Main class 上,为缓存添加了以下注释
@EnableCaching
public class Application {
根据 src/main/resources, ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd"
updateCheck="true" monitoring="autodetect" dynamicConfig="true">
<cache name="languageCache"
maxEntriesLocalHeap="20"
overflowToDisk="false"
eternal="false"
diskPersistent="false"
memoryStoreEvictionPolicy="LRU"/>
<cache name="countryCache"
maxEntriesLocalHeap="280"
overflowToDisk="false"
eternal="false"
diskPersistent="false"
memoryStoreEvictionPolicy="LRU"/>
..
..
more entries
</ehcache>
Cache Config file
@Configuration
@EnableCaching
public class CacheConfig {
@Bean
public CacheManager getEhCacheManager() {
(new EhCacheCacheManager(getEhCacheFactory().getObject())).getCache("languageCache");
return new EhCacheCacheManager(getEhCacheFactory().getObject());
}
@Bean
public EhCacheManagerFactoryBean getEhCacheFactory() {
EhCacheManagerFactoryBean factoryBean = new EhCacheManagerFactoryBean();
factoryBean.setConfigLocation(new ClassPathResource("ehcache.xml"));
factoryBean.setShared(true);
return factoryBean;
}
}
关于上述代码的几个问题:
1)是否由于这条线
factoryBean.setConfigLocation(new ClassPathResource(“ehcache.xml”));
除了Dev env之外的任何其他环境中都没有命中/使用缓存?
2)我们需要CacheConfig文件吗?或Spring启动会在主类上使用注释(@EnableCaching)检测Ehcache?
任何建议,为什么缓存没有被提取(某些配置我缺少?)在其他envs?
谢谢
1 回答
除非你的类路径中有很多
ehcache.xml
,否则它应该可行 . 除非你的类路径中有一个符合JSR107的实现(例如Ehcache 3),否则@EnableCaching
将无法使用魔法 .你的代码有效 . 唯一奇怪的部分是你自己打电话给
getObject()
. 它仍然有效,但我会做 .也就是说,事实上,我会做一些更简单的事情:
另外,请注意,您确实需要共享缓存管理器,这是很少见的 . 它已经在应用程序上下文中共享 . 因此,将它作为单身人士分享是非常罕见的(并且经常是危险的) .