【问题标题】:Incorrect ehcache statistics: hits+misses == 0不正确的 ehcache 统计信息:命中+未命中 == 0
【发布时间】:2011-07-12 22:30:29
【问题描述】:

我遇到net.sf.ehcache.CacheManager 出现返回无效统计信息的问题。

我正在使用ehcache-core v2.3.2(最新版本)和ehcache-spring-annotations

问题getMemoryStoreObjectCount返回1对象,而getCacheHitsgetCacheMisses都返回0。总计数不应该是 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

}

为了完整起见,我包括了所有必要的配置:

弹簧配置

<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(keyGenerator=@KeyGenerator(name="StringCacheKeyGenerator"))
public Entity getEntity(Serializable key) {
    return // sql ... 
}

【问题讨论】:

  • 嗨,您是否介意发布您的代码,说明您是如何从 Spring 配置中派生 JUnit 测试中的“缓存”变量的?

标签: java hibernate spring annotations ehcache


【解决方案1】:

&lt;defaultCache ... statistics="true" /&gt; 非常有用 与旧方式相比 cache.setStatisticsEnabled(true);这需要较低版本的ehcache(核心等)。

【讨论】:

    【解决方案2】:

    statistics="true" 添加到您的 ehcache.xml,通常最好将配置更改保留在代码之外。

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

    【讨论】:

      【解决方案3】:

      通过在net.sf.ehcache.hibernate.EhCache中设置以下属性找到了问题的解决方案:

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

      【讨论】:

      • 也许第二个不是必需的。
      • @Bozho,可能不是,但在测试中没关系。
      • 是的。我只是觉得值得一提。无论如何,答案是为我形成的,所以 +1。
      猜你喜欢
      • 2014-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-19
      • 2021-12-24
      • 2011-11-11
      • 2015-08-18
      • 1970-01-01
      相关资源
      最近更新 更多