3

I am using Hibernate 4.1.7 and EhCache as second level cache. I am implementing a rest service to clear cahce (evict all regions ) as needed.

Below is code snippet

org.hibernate.stat.Statistics statistics = HibernateUtil.getSessionFactory().getStatistics();
      statistics.setStatisticsEnabled(true);

      long hits = statistics.getSecondLevelCacheHitCount();
      long misses = statistics.getSecondLevelCacheMissCount();
      long puts = statistics.getSecondLevelCachePutCount();

      logger.info("Hits: " + hits + " Misses: " + misses +  " Puts:" + puts);


      cache.evictEntityRegions();

      hits = statistics.getSecondLevelCacheHitCount();
      misses = statistics.getSecondLevelCacheMissCount();
      puts = statistics.getSecondLevelCachePutCount();


      logger.info("Hits: " + hits + " Misses: " + misses +  " Puts:" + puts);         

      long hit0 = statistics.getQueryCacheHitCount();
      long miss0 = statistics.getSecondLevelCacheMissCount();

Unfortunately, I get same values for hits/misses and puts after I evict all regions.

4

1 回答 1

2

These counts have the following meaning:

  • Hits - the number of times Hibernate checked the cache for an object and that object was found, i.e. was already in the cache
  • Misses - the number of times Hibernate checked the cache for an object but that object was not found in the cache (so would need to be fetched from the database)
  • Puts - the number of times Hibernate put an object into the cache

These statistics don't give you the current number of items in the cache. With that in mind, clearing the cache wouldn't affect those numbers.

If you do want to reset the statistics, use

statistics.clear()

But if you want to check the actual size of the cache you can use

CacheManager.ALL_CACHE_MANAGERS.get(0).getCache("com.example.MyEntity").getSize();

Note that each entity has its own cache, which is named using the fully-qualified class name for the entity.

于 2018-04-18T23:52:56.377 回答