2011-03-10 55 views
13

我有一个问题,其中net.sf.ehcache.CacheManager显示返回无效统计信息。我使用ehcache-core v2.3.2(最新版本)与ehcache-spring-annotations不正确的ehcache统计信息:命中+未命中== 0

问题getMemoryStoreObjectCount返回对象同时兼具getCacheHitsgetCacheMisses返回。是不是总数应该是hits + misses

下面的单元测试应该说明问题(它应用于数据库):

@Test 
public void testCache() { 
    Entity e = .. 
    dao.storeEntity(e); 
    dao.getEntity(e); 
    assertEquals(1, cache.getStatistics().getMemoryStoreObjectCount()); // ok 
    assertEquals(0, cache.getStatistics().getCacheHits()); // ok 
    assertEquals(1, cache.getStatistics().getCacheMisses()); // fails due to 0 

} 

为了完整性我包括所有必需的结构:

Spring配置

<ehcache:annotation-driven cache-manager="ehCacheManager" /> 
<bean id="ehCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> 
    <property name="configLocation" value="classpath:ehcache.xml"/> 
</bean> 

ehcache.xml

<ehcache> 
    <defaultCache eternal="false" maxElementsInMemory="1000" 
     overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0" 
     timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU"/> 
</ehcache> 

@Cacheable([email protected](name="StringCacheKeyGenerator")) 
public Entity getEntity(Serializable key) { 
    return // sql ... 
} 
+0

嗨,你介意发布你的代码,关于如何从Spring配置中导出JUnit测试中的“缓存”变量? – Dave 2016-02-19 16:42:39

回答

14

找到解决问题的办法由net.sf.ehcache.hibernate.EhCache设置以下属性:

cache.setStatisticsEnabled(true); 
    cache.setStatisticsAccuracy(Statistics.STATISTICS_ACCURACY_GUARANTEED); 
+1

也许第二个不是必需的。 – Bozho 2011-03-22 22:08:00

+0

@Bozho,可能不会,但在测试中不会有问题。 – 2011-03-23 07:49:05

+0

是的。我只是觉得值得一提。无论如何,答案为我而形成,所以+1。 – Bozho 2011-03-23 08:14:07

15

添加统计= “真”你ehcache.xml中,通常更好的做法是将配置更改保留在代码之外。

<ehcache> 
    <defaultCache ... statistics="true" /> 
... 
</ehcache> 
5

<defaultCache ... statistics="true" />作品大大 与老办法对比cache.setStatisticsEnabled(真);需要更低版本的ehcache(核心等)。