Hibernate性能优化之EHCache缓存
像Hibernate这种ORM框架,相较于JDBC操作,需要有更复杂的机制来实现映射、对象状态管理等,因此在性能和效率上有一定的损耗。
在保证避免映射产生低效的SQL操作外,缓存是提升Hibernate的关键之一。
加入缓存可以避免数据库调用带来的连接创建与销毁、数据打包拆包、SQL执行、网络传输,良好的缓存机制和合理的缓存模式能带来性能的极大提升,EHCache就提供了这种良好的缓存机制。
在考虑给系统加入缓存进行优化前,复用SessionFactory是Hibernate优化最优先、最基础的性能优化方法,参考上一篇《Hibernate性能优化之SessionFactory重用》。
Hibernate的缓存机制
缓存的级别一般分为三种,每一种缓存的范围更大:
事务级缓存:Hibernate中称为一级缓存,在一个Session中共享缓存对象;
应用级缓存:Hibernate中称为二级缓存,在一个SessionFactory中共享缓存对象,SessionFactory在整个应用范围内重用;
分布式缓存:部署为单独的实例,如Redis、Memcache等。
Hibernate的按以下方式进行缓存:
当Hibernate根据ID访问数据对象的时候,首先从Session一级缓存中查;
查不到,如果配置了二级缓存,那么从二级缓存中查;
如果都查不到,再查询数据库,把结果按照ID放入到缓存删除、更新、增加数据的时候,同时更新缓存。
Hibernate默认不启用二级缓存,EHCache是Hibernate中的二级缓存插件,使用Hibernate的系统可以直接使用EHCache缓存。
为什么要直接使用EHCache
回头来看那句话:良好的缓存机制和合理的缓存模式能带来性能的极大提升。
Hibernate的缓存模式是什么?
根据ID来缓存对象,也就是Session的get、load操作时。
这种缓存模式的弊端有两点:
1、应用场景太单一,系统中大量的列表式查询缓存起不到作用;
2、一些系统中通过ThreadLocal在线程中重用Session,每个线程可能需要大量处理不用的业务逻辑,缓存命中率很低;如果不重用Session,一般的场景缓存命中率更低。
既然EHCache已经提供了良好的缓存机制,结合自己系统的业务来优化缓存模式才是最佳的。
如何使用EHCache
EHCache是Hibernate中的二级缓存插件,使用Hibernate的系统可以直接使用EHCache缓存,不需要再添加其他jar包。
新建EHCache配置文件,具体的配置含义可以查手册:
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd">
<diskStore path="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="10000"
maxElementsOnDisk="0"
eternal="true"
overflowToDisk="true"
diskPersistent="false"
timeToIdleSeconds="0"
timeToLiveSeconds="0"
diskSpoolBufferSizeMB="50"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LFU"
/>
<cache name="restCache"
maxElementsInMemory="100"
maxElementsOnDisk="0"
eternal="false"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="119"
timeToLiveSeconds="119"
diskSpoolBufferSizeMB="50"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="FIFO"
/>
</ehcache>
EHCache的一个优点是线程安全的,适合多线程的使用场景,能简化开发人员的使用。
因此我写了一个单例模式,避免每次在方法里写getCache,这个类也涵盖了EHCache的基本使用:
public class EHCacheFactory {
private final CacheManager manager;
private final Cache cache;
private EHCacheFactory() {
manager = CacheManager.create(getClass().getResource("/ehcache.xml"));
cache = manager.getCache("restCache");
}
public Element getCache(String strKey) {
return EHCacheFactory.getInstance().getCache().get(strKey);
}
public void setCache(String strKey, String strVal) {
EHCacheFactory.getInstance().getCache().put(new Element(strKey, strVal));
}
public Cache getCache() {
return cache;
}
private static class SingletonHolder {
private final static EHCacheFactory INSTANCE = new EHCacheFactory();
}
public static EHCacheFactory getInstance() {
return SingletonHolder.INSTANCE;
}
}
我的系统是JAVA REST,在需要缓冲的REST接口中加入了EHCache缓存,通过URL参数作为缓存键值,REST接口返回的json数据作为缓存值,这种缓存模式非常适合REST。
使用ab进行了简单的性能测试:
在一个简答查询接口中,性能提升一倍;
在一个略复杂接口中,执行4、5个查询,加入缓存后性能提升20倍。
介绍在Hibernate中使用查询缓存、一级缓存、二级缓存,
整合Spring在HibernateTemplate中使用查询缓存。
EhCache是Hibernate的二级缓存技术之一,可以把查询出来的数据存储在内存或者磁盘,节省下次同样查询语句再次查询数据库,大幅减轻数据库压力;
EhCache的使用注意点
当用Hibernate的方式修改表数据(save,update,delete等等),这时EhCache会自动把缓存中关于此表的所有缓存全部删除掉(这样能达到同步)。但对于数据经常修改的表来说,可能就失去缓存的意义了(不能减轻数据库压力);
在比较少更新表数据的情况下,EhCache一般要使用在比较少执行write操作的表(包括update,insert,delete等)[Hibernate的二级缓存也都是这样];对并发要求不是很严格的情况下,两台机子中的缓存是不能实时同步的;
首先要在hibernate.cfg.xml配置文件中添加配置,在hibernate.cfg.xml中的mapping标签上面加以下内容:
<!-- Hibernate 3.3 and higher -->
<!--
<property name="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.EhCacheRegionFactory</property>
<property name="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.SingletonEhCacheRegionFactory</property>
-->
<!-- hibernate3.0-3.2 cache config-->
<!--
<property name="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.EhCacheProvider</property>
-->
<property name="hibernate.cache.provider_class">net.sf.ehcache.hibernate.SingletonEhCacheProvider</property> <!-- Enable Second-Level Cache and Query Cache Settings -->
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.use_query_cache">true</property>
如果你是整合在spring配置文件中,那么你得配置你的applicationContext.xml中相关SessionFactory的配置
<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
然后在hibernate.cfg.xml配置文件中加入使用缓存的属性
<!-- class-cache config -->
<class-cache class="com.hoo.hibernate.entity.User" usage="read-write" />
当然你也可以在User.hbm.xml映射文件需要Cache的配置class节点下,加入类似如下格式信息:
<class name="com.hoo.hibernate.entity.User" table="USER" lazy="false">
<cache usage="transactional|read-write|nonstrict-read-write|read-only" />
注意:cache节点元素应紧跟class元素
关于选择缓存策略依据:
ehcache不支持transactional,其他三种可以支持。
read- only:无需修改, 可以对其进行只读缓存,注意:在此策略下,如果直接修改数据库,即使能够看到前台显示效果,但是将对象修改至cache中会报error,cache不会发生作用。另:删除记录会报错,因为不能在read-only模式的对象从cache中删除。
read-write:需要更新数据,那么使用读/写缓存比较合适,前提:数据库不可以为serializable transaction isolation level(序列化事务隔离级别)
nonstrict-read-write:只偶尔需要更新数据(也就是说,两个事务同时更新同一记录的情况很不常见),也不需要十分严格的事务隔离,那么比较适合使用非严格读/写缓存策略。
如果你使用的注解方式,没有User.hbm.xml,那么你也可以用注解方式配置缓存
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class User implements Serializable {
}
在Dao层使用cache,代码如下
Session s = HibernateSessionFactory.getSession();
Criteria c = s.createCriteria(User.class);
c.setCacheable(true);//这句必须要有
System.out.println("第一次读取");
List<User> users = c.list();
System.out.println(users.size());
HibernateSessionFactory.closeSession(); s = HibernateSessionFactory.getSession();
c = s.createCriteria(User.class);
c.setCacheable(true);//这句必须要有
System.out.println("第二次读取");
users = c.list();
System.out.println(users.size());
HibernateSessionFactory.closeSession();
你会发现第二次查询没有打印sql语句,而是直接使用缓存中的对象。
如果你的Hibernate和Spring整合在一起,那么你可以用HibernateTemplate来设置cache
getHibernateTemplate().setCacheQueries(true);
return getHibernateTemplate().find("from User");
当你整合Spring时,如果你的HibernateTemplate模板配置在Spring的Ioc容器中,那么你可以这样启用query cache
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
<property name="cacheQueries">
<value>true</value>
</property>
</bean>
此后,你在dao模块中注入sessionFactory的地方都注入hibernateTemplate即可。
以上讲到的都是Spring和Hibernate的配置,下面主要结合上面使用的ehcache,来完成ehcache.xml的配置。如果你没有配置ehcache,默认情况下使用defaultCache的配置。
<cache name="com.hoo.hibernate.entity.User" maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="300" timeToLiveSeconds="600" overflowToDisk="true" />
<!--
hbm文件查找cache方法名的策略:如果不指定hbm文件中的region="ehcache.xml中的name的属性值",则使用name名为com.hoo.hibernate.entity.User的cache,如果不存在与类名匹配的cache名称,则用 defaultCache。
如果User包含set集合,则需要另行指定其cache
例如User包含citySet集合,则需要
添加如下配置到ehcache.xml中
-->
<cache name="com.hoo.hibernate.entity.citySet"
maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="300"
timeToLiveSeconds="600" overflowToDisk="true" />
如果你使用了Hibernate的查询缓存,需要在ehcache.xml中加入下面的配置
<cache name="org.hibernate.cache.UpdateTimestampsCache"
maxElementsInMemory="5000"
eternal="true"
overflowToDisk="true" />
<cache name="org.hibernate.cache.StandardQueryCache"
maxElementsInMemory="10000"
eternal="false"
timeToLiveSeconds="120"
overflowToDisk="true" />
调试时候使用log4j的log4j.logger.org.hibernate.cache=debug,更方便看到ehcache的操作过程,主要用于调试过程,实际应用发布时候,请注释掉,以免影响性能。
使用ehcache,打印sql语句是正常的,因为query cache设置为true将会创建两个缓存区域:一个用于保存查询结果集 (org.hibernate.cache.StandardQueryCache); 另一个则用于保存最近查询的一系列表的时间戳(org.hibernate.cache.UpdateTimestampsCache)。请注意:在查询缓存中,它并不缓存结果集中所包含的实体的确切状态;它只缓存这些实体的标识符属性的值、以及各值类型的结果。需要将打印sql语句与最近的cache内 容相比较,将不同之处修改到cache中,所以查询缓存通常会和二级缓存一起使用。
二级缓存是属于SessionFactory级别的缓存机制,是属于进程范围的缓存。一级缓存是Session级别的缓存,是属于事务范围的缓存,由Hibernate管理,一般无需进行干预。
Hibernate支持以下的第三方的缓存框架:
| Cache | Interface | Supported strategies | ||
|---|---|---|---|---|
| HashTable (testing only) |
|
|||
| EHCache |
|
|||
| OSCache |
|
|||
| SwarmCache |
|
|||
| JBoss Cache 1.x |
|
|||
| JBoss Cache 2.x |
|
2、下载第三方ehcache.jar
ehcache.jar包的话,有两种,一种是org.ehcache,另一种是net.sf.ehache。Hibernate集成的是net.sf.ehcache!!所以应该下载net.sf.ehcache。如果使用org.ehcache的jar包,hibernate是不支持的!!
下载下来的jar包,需要放到项目当中,在本案例,是放到SSHWebProject项目的WebRoot/WEB-INF/lib目录下,需要注意的是,ehcache.jar包依赖commons-logging.jar,你还得看看你项目中有没有commons-logging.jar!!


3、开启hibernate的二级缓存
想是否使用hibernate.cfg.xml配置文件,会导致配置使用二级缓存的方式不一样,一般是由于项目集成了Spring框架,所以配置二级缓存的话,
就分以下两种情况:
1)项目有hibernate.cfg.xml
1-1)开启Hibernate缓存二级缓存功能
修改hibernate.cfg.xml,添加以下内容
Users.hbm.xml,添加以下内容:
2)集成了Spring框架之后,没有hibenate.cfg.mlx文件
1-1)开启Hibernate缓存二级缓存功能
修改applicationContext.xml文件,在sessionFactory Bean中添加以下hibernateProperties,如下:
1-2)配置哪些实体类的对象需要存放到二级缓存
本案例中,以edu.po.Users用户对象为例子,对应的实体映射文件为Users.hbm.xml。
在hbm文件(实体映射文件)中配置
Users.hbm.xml,添加以下内容:
<cache usage="read-write"/>
4、配置ehcache.xml文件
将ehcache.jar包中的ehcache-failsafe.xml 改名为 ehcache.xml 放入 src,因为hibernate默认找classpath*:ehcache.xml
本案例,对<diskStore>和<defaultCache>进行修改,如下
<diskStore path="d:/EhCacheData"/>
<!--
maxElementsInMemory: 内存中最大对象数量 ,超过数量,数据会被缓存到硬盘
eternal:缓存的对象是否有有效期(即是否永久存在)。如果为true,timeouts属性被忽略
timeToIdleSeconds:缓存的对象在过期前的空闲时间,单位秒
timeToLiveSeconds:存活时间,对象不管是否使用,到了时间回收,单位秒
overflowToDisk:当内存中缓存对象数量达到 maxElementsInMemory 限制时,是否可以写到硬盘
maxElementsOnDisk:硬盘缓存最大对象数量
diskPersistent:在java虚拟机(JVM)重启或停掉的时候,是否持久化磁盘缓存,默认是false
diskExpiryThreadIntervalSeconds:清除磁盘缓存中过期对象的监听线程的运行间隔,默认是120秒
memoryStoreEvictionPolicy:当内存缓存的对象数量达到最大,有新的对象要加入的时候,
移除缓存中对象的策略。默认是LRU,可选的有LFU和FIFO
-->
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
diskPersistent="true"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"
/>
5、demo
SpringBeanUtils.java:
package utils; import org.apache.log4j.Logger;
import org.hibernate.SessionFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext; /**
* Title: SpringBeanUtils.java
* Description: 获取Spring的Bean实例对象的工具类
* @author yh.zeng
* @date 2017-6-27
*/
public class SpringBeanUtils { private static Logger logger = Logger.getLogger(SpringBeanUtils.class); static String filePath ="WebRoot/WEB-INF/applicationContext.xml";
static ApplicationContext CONTEXT ;
static{
try{
CONTEXT = new FileSystemXmlApplicationContext(filePath);
}catch(Exception e){
logger.error(StringUtils.getExceptionMessage(e));
}
} /**
* 获取Bean
* @param uniqueIdentifier Bean的唯一标识,可以是ID也可以是name
* @return
*/
public static Object getBean(String uniqueIdentifier){
return CONTEXT.getBean(uniqueIdentifier);
} /**
* 获取SessionFacotry对象
* @param uniqueIdentifier SessionFactory Bean的唯一标识,可以是ID也可以是name
* @return
*/
public static SessionFactory getSessionFactory(String uniqueIdentifier){
return (SessionFactory) CONTEXT.getBean(uniqueIdentifier);
} public static String getFilePath() {
return filePath;
} public static void setFilePath(String filePath) {
SpringBeanUtils.filePath = filePath;
CONTEXT = new FileSystemXmlApplicationContext(filePath);
} }
HibernateEhCacheTest.java:
注意:查询缓存和查看Cache(缓存)统计信息的功能,需要做另外配置,见博客Hibernate开启查询缓存、Hibernate开启收集缓存统计信息
项目demo: https://github.com/zengyh/SSHWebProject.git
参考:在Spring、Hibernate中使用Ehcache缓存
Hibernate性能优化之EHCache缓存的更多相关文章
- Hibernate 性能优化之二级缓存
二级缓存是一个共享缓存,在二级缓存中存放的数据是共享数据特性 修改不能特别频繁 数据可以公开二级缓存在sessionFactory中,因为sessionFactory本身是线程安全,所 ...
- Hibernate 性能优化之一级缓存
1.一级缓存的生命周期 一级缓存在session中存放,只要打开session,一级缓存就存在了,当session关闭的时候,一级缓存就不存在了 2.一级缓存是依赖于谁存在的 ...
- Hibernate 性能优化之查询缓存
查询缓存是建立在二级缓存基础之上的,所以与二级缓存特性相似,是共享的,适合修改不是很频繁的数据 查询缓存不是默认开启的,需要设置 1.在cfg文件中配置 <property name= ...
- [MySQL性能优化系列]提高缓存命中率
1. 背景 通常情况下,能用一条sql语句完成的查询,我们尽量不用多次查询完成.因为,查询次数越多,通信开销越大.但是,分多次查询,有可能提高缓存命中率.到底使用一个复合查询还是多个独立查询,需要根据 ...
- 8.Hibernate性能优化
性能优化 1.注意session.clear() 的运用,尤其在不断分页的时候 a) 在一个大集合中进行遍历,遍历msg,取出其中额含有敏感字样的对象 b) 另外一种形式的内存泄漏( //面试题:Ja ...
- 第七章 Hibernate性能优化
一对一关联 实体类关系 一对多 多对多 一对一 Hibernate提供了两种映射一对一关联关系的方式:按照外键映射和按照主键映射.下面以员工账号和员工档案表为例,介绍这两种映射方式,并使用这两种映射方 ...
- SQL性能优化前期准备-清除缓存、开启IO统计
文章来至:https://www.cnblogs.com/Ren_Lei/p/5669662.html 如果需要进行SQl Server下的SQL性能优化,需要准备以下内容: 一.SQL查询分析器设置 ...
- 秋色园QBlog技术原理解析:性能优化篇:缓存总有失效时,构造持续的缓存方案(十四)
转载自:http://www.cyqdata.com/qblog/article-detail-38993 文章回顾: 1: 秋色园QBlog技术原理解析:开篇:整体认识(一) --介绍整体文件夹和文 ...
- OpenStack入门篇(五)之KVM性能优化及IO缓存介绍
1.KVM的性能优化,介绍CPU,内存,IO性能优化 KVM CPU-->qemu进行模拟ring 3-->用户应用 (用户态,用户空间)ring 0-->操作系统 (内核态,内核空 ...
随机推荐
- OpenCV——SIFT特征检测与匹配
SIFT特征和SURF特征比较 比较项目 SIFT SURF 尺度空间极值检测 使用高斯滤波器,根据不同尺度的高斯差(DOG)图像寻找局部极值 使用方形滤波器,利用海森矩阵的行列式值检测极值,并利用积 ...
- PAT B1010 一元多项式求导 (25 分)
设计函数求一元多项式的导数.(注:xn(n为整数)的一阶导数为nxn−1.) 输入格式: 以指数递降方式输入多项式非零项系数和指数(绝对值均为不超过 1000 的整数).数字间以空格分隔. ...
- Arduino入门笔记(1):认识Arduino
转载请注明:@小五义http://www.cnblogs.com/xiaowuyi 欢迎加入讨论群 64770604 各种网站论坛里经常看到网友DIY各种遥控小车.机器人什么的,一直很好奇,很想学习一 ...
- 20155204 王昊《网络对抗技术》EXP4
20155204 王昊<网络对抗技术>EXP4 一.实验后回答问题 (1)如果在工作中怀疑一台主机上有恶意代码,但只是猜想,所有想监控下系统一天天的到底在干些什么.请设计下你想监控的操作有 ...
- POJ 3349&&3274&&2151&&1840&&2002&&2503
(今天兴致大发学了Markdown,第一篇博客) 这次的主要都是hash的题目(当然这就意味这可以用map) hash的方式也有很多: 普通hash hash挂链 双hash以及自然溢出等 当然我还是 ...
- kali2.0 使用SSH进行远程登录
工具/原料 kali 2.0 ssh SSH连接工具(XShell) 一.配置SSH参数 修改sshd_config文件,命令为: vi /etc/ssh/sshd_config 将#Passwo ...
- Invitation Cards POJ-1511 (spfa)
题目链接:Invitation Cards 题意: 给出一张有向图,现在要求从1到其他所有的结点的最小路径和与从所有其他结点到1的最小路径和之和. 题解: 求最小路径可以用SPFA来求解.从1到其他结 ...
- libgdx学习记录17——照相机Camera
照相机在libgdx中的地位举足轻重,贯穿于整个游戏开发过程的始终.一般我们都通过Stage封装而间接使用Camera,同时我们也可以单独使用Camera以完成背景的移动.元素的放大.旋转等操作. C ...
- 利用fiddler core api 拦截修改 websocket 数据
一般的中间人攻击基本都是拦截修改普通的http协议里面的内容,而对于怎么拦截修改websocket协议传输的内容好像都没有多少介绍. talk is cheap show me the code us ...
- 11、Dockerfile实战-Tomcat
一.编写Dockerfile 具体步骤这里不再细说,直接看Dockerfile文件: FROM centos:7 MAINTAINER QUNXUE ENV VERSION=8.0.46 RUN yu ...