hibernate ehcache的配置使用



一:基本介绍及使用


1.EhCache是什么
    EhCache是Hibernate的二级缓存技术之一,可以把查询出来的数据存储在内存或者磁盘,节省下次同样查询语句再次查询数据库,大幅减轻数据库压力;

2.EhCache的使用注意点
    当用Hibernate的方式修改表数据(save,update,delete等等),这时EhCache会自动把缓存中关于此表的所有缓存全部删除掉(这样能达到同步)。但对于数据经常修改的表来说,可能就失去缓存的意义了(不能减轻数据库压力);

3.EhCache使用的场合
    3.1比较少更新表数据
        EhCache一般要使用在比较少执行write操作的表(包括update,insert,delete等)[Hibernate的二级缓存也都是这样];
    3.2对并发要求不是很严格的情况
        两台机子中的缓存是不能实时同步的;

4.在项目做的实现
    4.1在工程的src目录下添加ehcache.xml文件,内容如下:
        <?xml version="1.0" encoding="UTF-8"?>
        <ehcache>    
            <diskStore path="java.io.tmpdir" />
          <defaultCache maxElementsInMemory="5"<!--缓存可以存储的总记录量-->
            eternal="false"<!--缓存是否永远不销毁-->
            overflowToDisk="true"<!--当缓存中的数据达到最大值时,是否把缓存数据写入磁盘-->
            timeToIdleSeconds="15"<!--当缓存闲置时间超过该值,则缓存自动销毁-->
                timeToLiveSeconds="120"<!--缓存创建之后,到达该缓存自动销毁-->
          />
        </ehcache>


    4.2在Hibernate.cfg.xml中的mapping标签上面加以下内容:
        <property name="show_sql">true</property>
        <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
        <property name="hibernate.cache.use_query_cache">true</property>


    4.3在要缓存的bean的hbm.xml文件中的class标签下加入以下内容:
       <cache usage="read-only" /><!--也可读写-->


    4.4创建DAO,内容如下:
        Session s = HibernateSessionFactory.getSession();
        Criteria c = s.createCriteria(Xyz.class);
        c.setCacheable(true);//这句必须要有
        System.out.println("第一次读取");
        List l = c.list();
        System.out.println(l.size());
        HibernateSessionFactory.closeSession();


        s = HibernateSessionFactory.getSession();
        c = s.createCriteria(Xyz.class);
        c.setCacheable(true);//这句必须要有
        System.out.println("第二次读取");
        l = c.list();
        System.out.println(l.size());
        HibernateSessionFactory.closeSession();


   4.5这时你会看到打印出来的信息为(表示第二次并没有去读库):
        第一次读取
        Hibernate: *******
        13
        第二次读取
        13








二:配置Spring+hibernate使用ehcache作为second-level cache

大量数据流动是web应用性能问题常见的原因,而缓存被广泛的用于优化数据库应用。cache被设计为通过保存从数据库里load的数据来减少应用和数据 库之间的数据流动。数据库访问只有当检索的数据不在cache里可用时才必要。hibernate可以用两种不同的对象缓存:first-level cache 和 second-level cache。first-level cache和Session对象关联,而second-level cache是和Session Factory对象关联。

        缺省地,hibernate已经使用基于每个事务的first-level cache。 Hibernate用first-level cache主要是减少在一个事务内的sql查询数量。例如,如果一个对象在同一个事务内被修改多次,hibernate将只生成一个包括所有修改的 UPDATE SQL语句。为了减少数据流动,second-level cache在Session Factory级的不同事务之间保持load的对象,这些对象对整个应用可用,不只是对当前用户正在运行的查询。这样,每次查询将返回已经load在缓存 里的对象,避免一个或更多潜在的数据库事务。

下载ehcache,hibernate3.2必须要ehcache1.2以上才能支持。可以修改log4j配置文件log4j.logger.net.sf.hibernate.cache=debug查看日志


1,配置ehcache.xml文件,放在classpath下(默认读取classpath下ehcache.xml)
<ehcache>
     <!-- 配置硬盘文件缓存地址 -->  
     <diskStore path="java.io.tmpdir"/>
	<!-- 配置硬盘文件缓存地址 -->     
	<diskStore path="java.io.tmpdir" />

	<!-- 默认缓存 defaultCache
		参数详解:
		maxElementsInMemory=“10000” //Cache中最多允许保存的数据对象的数量
		external=“false” //缓存中对象是否为永久的,如果是,超时设置将被忽略,对象从不过期 
		timeToIdleSeconds=“1000”  //缓存数据钝化时间(设置对象在它过期之前的空闲时间)  
		timeToLiveSeconds=“1000”  //缓存数据的生存时间(设置对象在它过期之前的生存时间)
		overflowToDisk=“false” />    //内存不足时,是否启用磁盘缓存  
		memoryStoreEvictionPolicy="LRU" //内存不足时数据对象的清除策略
		ehcache中缓存的3种清空策略:
 			FIFO(first in first out):先进先出
 			LFU( Less Frequently Used):一直以来最少被使用的。如上面所讲,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。
 			LRU(Least Recently Used):最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,
						那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
	-->
     <defaultCache
         maxElementsInMemory="10000"
         eternal="false"
         overflowToDisk="true"
         timeToIdleSeconds="120"
         timeToLiveSeconds="120"
         diskPersistent="false"
         diskExpiryThreadIntervalSeconds="120"
	 memoryStoreEvictionPolicy="LRU" />

</ehcache>


2.hibernate.cfg.xml里Hibernate SessionFactory配置:
<session-factory>
	<!-- 指定cache实现类 --> 
	<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
	<!-- 启用二级缓存 -->  
	<property name="hibernate.cache.use_second_level_cache">true</property>
	<!-- 启用查询缓存 -->    
	<property name="hibernate.cache.use_query_cache">true</property>
	<!--指定ehcache配置文件,默认加载classpath下的:ehcache.xml -->
	<!--<property name="hibernate.cache.provider_configuration_file_resource_path">ehcache.xml</property>-->
</session-factory>



如果你是整合在spring配置文件中,那么你得配置你的applicationContext.xml中相关SessionFactory的配置
<!-- Hibernate SessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
	<property name="dataSource" ref="dataSource"/>
	<property name="configLocation"><value>classpath:hibernate.cfg.xml</value></property>
	<property name="hibernateProperties">
		<props>
			<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>
			<!--指定ehcache配置文件,默认加载classpath下的:ehcache.xml -->
			<prop key="hibernate.cache.provider_configuration_file_resource_path">ehcache.xml</prop>-->
		</props>
	</property>
</bean>



说明:如果不设置“查询缓存”,那么hibernate只会缓存使用load()方法获得的单个持久化对象,如果想缓存使用findall()、 list()、Iterator()、createCriteria()、createQuery()等方法获得的数据结果集的话,就需要设置 hibernate.cache.use_query_cache true 才行


3,使用cache的配置
<cache usage="read-write" region="ehcache.xml中的name的属性值"/>
Javabean cache的配置有三种,具体如下:
        (1).bean中注解配置的方式: 
		@Entity  
		@Table(name = "MY_TB_EH_BLOG_TOPIC")  
		@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
		public class EhBlogTopic implements Serializable {}		
        (2).hibernate.cfg.xml中标签配置方式:
		<session-factory>
			<class-cache class="" usage="read-write" />
		</session-factory>
        (3).映射文件*.hb.xml中标签配置方式:
		<class name="com.hoo.hibernate.entity.User" table="USER" lazy="false">
			<cache usage="transactional|read-write|nonstrict-read-write|read-only" />
		<class>
		注意:cache节点元素应紧跟class元素



关于选择缓存策略依据:
ehcache不支持transactional,其他三种可以支持。
read- only:无需修改, 可以对其进行只读缓存,注意:在此策略下,如果直接修改数据库,即使能够看到前台显示效果,但是将对象修改至cache中会报error,cache不                               会发生作用。另:删除记录会报错,因为不能在read-only模式的对象从cache中删除。
read-write:需要更新数据,那么使用读/写缓存比较合适,前提:数据库不可以为serializable transaction isolation level(序列化事务隔离级别)
nonstrict-read-write:只偶尔需要更新数据(也就是说,两个事务同时更新同一记录的情况很不常见),也不需要十分严格的事务隔离,那么比较适合使用非严格读/写缓存                                               策略。



4.对于"query cache",需要在程序里编码:
         getHibernateTemplate().setCacheQueries(true);
         return getHibernateTemplate().find(hql);





三:使用spring和hibernate配置ehcache和query cache



1、applicationContext.xml

这两句加到hibernateProperties中:
<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>

添加此bean到applicationcontext.xml中:
<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的bean中,更改如下:
<property name="sessionFactory">
	<ref bean="sessionFactory" />
</property>
改为
<property name="hibernateTemplate">
	<ref bean="hibernateTemplate" />
</property>



2、上面的ehcache.xml文件放在classes根目录即可


3、pojo(实体类)与ehcache.xml的配置关系

以com.hoo.hibernate.entity.User为例子
在User.hbm.xml中配置:
	<class name="com.hoo.hibernate.entity.User" table="table_u" lazy="false">
		<!-- region="ehcache.xml中的name的属性值" -->
		<cache usage="read-write" region="com.hoo.hibernate.entity.User"/>
	</class>
注意:这一句需要紧跟在class标签下面,其他位置无效。

<!--
hbm文件查找cache方法名的策略:
如果不指定hbm文件中的region="ehcache.xml中的name的属性值",则使用name名为com.hoo.hibernate.entity.User的cache,
如果不存在与类名匹配的cache名称,则用 defaultCache。
如果User包含set集合,则需要另行指定其cache
例如User包含citySet集合,则需要添加如下配置到ehcache.xml中

-->


<!-- 配置某个实体缓存,需要在ehcache.xml中加入下面的配置(例如:缓存User实体)-->
<cache name="com.hoo.hibernate.entity.User" 
	maxElementsInMemory="10000" 
	eternal="false" 
	timeToIdleSeconds="300" 
	timeToLiveSeconds="600" 
	overflowToDisk="true" />


<!--
如果User包含set集合,则需要另行指定其cache,
例如User包含citySet集合,则需要添加如下配置到ehcache.xml中
-->
<cache name="com.hoo.hibernate.entity.User.citySet"
	maxElementsInMemory="10000" 
	eternal="false" 
	timeToIdleSeconds="300"
	timeToLiveSeconds="600" 
	overflowToDisk="true" />

<!--
另,针对查询缓存还需要如下配置:
-->

<!--hibernate的查询缓存 -->
<cache name="org.hibernate.cache.StandardQueryCache"
	maxElementsInMemory="10000"
	eternal="false"
	timeToLiveSeconds="120"
	overflowToDisk="true"/>
<!-- hibernate的更新缓存-->
<cache name="org.hibernate.cache.UpdateTimestampsCache"
	maxElementsInMemory="5000"
	eternal="true"
	overflowToDisk="true"/>


4、选择缓存策略依据:

<cache usage="transactional|read-write|nonstrict-read-write|read-only" />
ehcache不支持transactional,其他三种可以支持。
read- only:无需修改, 那么就可以对其进行只读 缓存,注意,在此策略下,如果直接修改数据库,即使能够看到前台显示效果,但是将对象修改至cache中会报error,cache不会发生作用。另:删 除记录会报错,因为不能在read-only模式的对象从cache中删除。
read-write:需要更新数据,那么使用读/写缓存 比较合适,前提:数据库不可以为serializable transaction isolation level(序列化事务隔离级别)
nonstrict-read-write:只偶尔需要更新数据(也就是说,两个事务同时更新同一记录的情况很不常见),也不需要十分严格的事务隔离,那么比较适合使用非严格读/写缓存策略。


5、调试

调试时候使用log4j的log4j.logger.org.hibernate.cache=debug,更方便看到ehcache的操作过程,主要用于调试过程,实际应用发布时候,请注释掉,以免影响性能。



6、 使用ehcache,打印sql语句

使用ehcache,打印sql语句是正常的,因为query cache设置为true将会创建两个缓存区域:一个用于保存查询结果集 (org.hibernate.cache.StandardQueryCache); 另一个则用于保存最近查询的一系列表的时间戳(org.hibernate.cache.UpdateTimestampsCache)。请注意:在查询 缓存中,它并不缓存结果集中所包含的实体的确切状态;它只缓存这些实体的标识符属性的值、以及各值类型的结果。需要将打印sql语句与最近的cache内 容相比较,将不同之处修改到cache中,所以查询缓存通常会和二级缓存一起使用。












  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值