2011-03-10 50 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(核心等)。