使用 Spring 引导的 Ehcache 在测试环境中不工作

Ehcache with Spring boot is not working in Test env

我正在使用 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> 

缓存配置文件

@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(新ClassPathResource("ehcache.xml"));

在 Dev env 之外的任何其他环境中都没有命中/使用缓存?

2) 我们是否需要 CacheConfig 文件?或 Spring 启动将在 Main Class?

上使用注释(@EnableCaching)检测 Ehcache

任何建议,为什么在其他环境中没有获取缓存(我缺少某些配置?)?

谢谢

除非您的类路径中有许多 ehcache.xml,否则它应该可以工作。 @EnableCaching 除非您的类路径中有符合 JSR107 的实现(例如 Ehcache 3),否则不会神奇地工作。

您的代码有效。唯一奇怪的部分是您自己调用 getObject() 。它仍然有效,但我会这样做。

@Bean
public CacheManager cacheManager(net.sf.ehcache.CacheManager cacheManager) {
  return new EhCacheCacheManager(cacheManager);
}

@Bean
public EhCacheManagerFactoryBean cacheManagerFactory() {
  EhCacheManagerFactoryBean factoryBean = new EhCacheManagerFactoryBean();
  factoryBean.setConfigLocation(new ClassPathResource("ehcache.xml"));
  factoryBean.setShared(true);
  return factoryBean;
}

也就是说,事实上,我会做一些更简单的事情:

@Configuration
@EnableCaching
public class CacheConfig extends CachingConfigurerSupport {

    @Bean
    @Override
    public CacheManager cacheManager() {
        return  new EhCacheCacheManager(new net.sf.ehcache.CacheManager());
    }
}

另外,请注意,真的真的很少有人真正需要共享缓存管理器。它已经在应用程序上下文中共享。因此,将其作为单例共享是非常罕见的(而且经常是危险的)。