我使用 Hibernate 4.1.7 和 EhCache 作为二级缓存。我正在实现一项休息服务,以根据需要清除 cahce(驱逐所有区域)。
下面是代码片段
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();
不幸的是,在驱逐所有区域后,我得到了命中/未命中和放置的相同值。
最佳答案
这些计数具有以下含义:
- Hits - Hibernate 检查缓存中某个对象并找到该对象(即已在缓存中)的次数
- 未命中数 - Hibernate 检查缓存中某个对象但在缓存中未找到该对象(因此需要从数据库中获取)的次数
- Puts - Hibernate 将对象放入缓存的次数
这些统计信息不会为您提供缓存中当前项目的数量。考虑到这一点,清除缓存不会影响这些数字。
如果您确实想要重置统计信息,请使用
statistics.clear()
但是如果你想检查缓存的实际大小,你可以使用
CacheManager.ALL_CACHE_MANAGERS.get(0).getCache("com.example.MyEntity").getSize();
请注意,每个实体都有自己的缓存,该缓存使用实体的完全限定类名来命名。
关于Hibernate二级缓存: Not able to evict,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49908890/