加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – Hibernate二级缓存似乎无法正常工作

发布时间:2020-12-14 17:43:15 所属栏目:Java 来源:网络整理
导读:我目前正在尝试使用hibernate附带的缓存提供程序来运行hibernate. net.sf.ehcache.hibernate.SingletonEhCacheProvider 我在ecache.xml中启用了默认缓存和类特定缓存,该缓存在我的hibernate.cfg.xml文件中引用.定义类/映射文件特定高速缓存以处理多达20000个
我目前正在尝试使用hibernate附带的缓存提供程序来运行hibernate.
net.sf.ehcache.hibernate.SingletonEhCacheProvider

我在ecache.xml中启用了默认缓存和类特定缓存,该缓存在我的hibernate.cfg.xml文件中引用.定义类/映射文件特定高速缓存以处理多达20000个对象.

但是,我发现自从我在其中一个映射文件上打开缓存映射后,我没有看到这个问题.

我的测试如下.

加载我测试的特定映射文件的10000个对象(这应该击中DB并成为瓶颈).
接下来我将加载相同的10000个对象,因为我希望缓存被击中并看到显着的性能提升.尝试过使用hibernate映射xml文件中的“只读”和“读写”缓存映射.

我想知道他们需要做些什么来确保缓存在加载对象时在数据库之前被击中?

注意作为测试im pagin的一部分通过这些10000记录使用类似于下面的东西(在时间分页1000条记录).

Criteria crit = HibernateUtil.getSession() .createCriteria( persistentClass );
       crit.setFirstResult(startIndex);
       crit.setFetchSize(fetchSize);
       return crit.list();

已经看到标准有一个缓存模式setter(setCacheMode())所以我应该做些什么?

我注意到使用下面的统计代码,在内存中有10000个对象(好的hiberante脱水onjects,我想象??)
由于某种原因,我得到0次点击,更令人担忧的是0次失败所以看起来它看起来根本没有进入缓存,当它查看时,即使统计代码似乎告诉我内存中有10000个对象.

关于我在做什么的任何想法?我认为我得失的事实很好,因为它意味着正在使用缓存,但我无法弄清楚为什么我没有得到任何缓存命中.是否使用带有条件的setFirstResult()和setFetchSize()这一事实.

System.out.println("Cache Misses = " + stats.getSecondLevelCacheMissCount());
System.out.println("Cache Hits Count = " + stats.getSecondLevelCacheHitCount());

System.out.println("2nd level elements in mem "+ stats.getSecondLevelCacheStatistics("com.SomeTestEntity").getElementCountInMemory());

解决方法

二级缓存适用于“按主键查找”.对于其他查询,您需要缓存查询(假设启用了查询缓存),在您的情况下使用 Criteria#setCacheable(boolean)
Criteria crit = HibernateUtil.getSession().createCriteria( persistentClass );
crit.setFirstResult(startIndex);
crit.setFetchSize(fetchSize);
crit.setCachable(true); // Enable caching of this query result
return crit.list();

我建议阅读:

> Hibernate: Truly Understanding the Second-Level and Query Caches

If I cache the query,are all them hibernate entities from the query then available in the second level cache?

是他们会.我在上面提到的链接中用黑色解释了这一点:“请注意,查询缓存不会缓存结果集中实际实体的状态;它只缓存标识符值和值类型的结果.因此查询缓存应始终为与二级缓存一起使用“.你读过它吗?

As i was under the impression that using the query cache was entirely different than using the hibernate 2nd level cache.

它是不同的(用于缓存entrie的“密钥”是不同的).但查询缓存依赖于L2缓存.

From your answer you seem to be suggesting that the query cache and second level cache are both the same,and to generate cache hits I need to be using the “find by primary key”.

我只是说你需要缓存查询,因为你不是“通过主键查找”.我不清楚什么不清楚.您是否尝试在查询或条件对象上调用setCacheable(true)?很抱歉坚持但是,您是否阅读了我发布的链接?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读