在Spring、Hibernate中使用Ehcache缓存

来源:互联网 发布:绍兴网络电视台回看 编辑:程序博客网 时间:2024/05/17 07:04

前一篇 http://blog.csdn.net/gaowenhui2008/article/details/40044589 介绍了Ehcache整合Spring缓存,使用页面、对象缓存;这里将介绍在Hibernate中使用查询缓存、一级缓存、二级缓存,整合Spring在HibernateTemplate中使用查询缓存。

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


EhCache的使用注意点

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

 

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

 

首先要在hibernate.cfg.xml配置文件中添加如下配置

[html] view plaincopyprint?
  1. 在Hibernate.cfg.xml中的mapping标签上面加以下内容:  
  2. <!--  Hibernate 3.3 and higher -->    
  3. <!--     
  4. <property name="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.EhCacheRegionFactory</property>  
  5. <property name="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.SingletonEhCacheRegionFactory</property>  
  6. -->    
  7. <!-- hibernate3.0-3.2 cache config-->    
  8. <!--     
  9. <property name="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.EhCacheProvider</property>   
  10. -->    
  11. <property name="hibernate.cache.provider_class">net.sf.ehcache.hibernate.SingletonEhCacheProvider</property>    
  12.              
  13. <!-- Enable Second-Level Cache and Query Cache Settings -->    
  14. <property name="hibernate.cache.use_second_level_cache">true</property>    
  15. <property name="hibernate.cache.use_query_cache">true</property>  

如果你是整合在spring配置文件中,那么你得配置你的applicationContext.xml中相关SessionFactory的配置

[html] view plaincopyprint?
  1. <prop key="hibernate.cache.use_query_cache">true</prop>  
  2. <prop key="hibernate.cache.use_second_level_cache">true</prop>  
  3. <prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>  

然后在hibernate.cfg.xml配置文件中加入使用缓存的属性

[html] view plaincopyprint?
  1. <!-- class-cache config -->    
  2. <class-cache class="com.hoo.hibernate.entity.User" usage="read-write" />  

当然你也可以在User.hbm.xml映射文件需要Cache的配置class节点下,加入类似如下格式信息:

[html] view plaincopyprint?
  1. <class name="com.hoo.hibernate.entity.User" table="USER" lazy="false">  
  2. <cache usage="transactional|read-write|nonstrict-read-write|read-only" />  
  3. 注意:cache节点元素应紧跟class元素  


关于选择缓存策略依据:

ehcache不支持transactional,其他三种可以支持。

read-only:无需修改, 可以对其进行只读缓存,注意:在此策略下,如果直接修改数据库,即使能够看到前台显示效果,但是将对象修改至cache中会报error,cache不会发生作用。另:删除记录会报错,因为不能在read-only模式的对象从cache中删除。

read-write:需要更新数据,那么使用读/写缓存比较合适,前提:数据库不可以为serializable transaction isolationlevel(序列化事务隔离级别)

nonstrict-read-write:只偶尔需要更新数据(也就是说,两个事务同时更新同一记录的情况很不常见),也不需要十分严格的事务隔离,那么比较适合使用非严格读/写缓存策略。

 

如果你使用的注解方式,没有User.hbm.xml,那么你也可以用注解方式配置缓存

[java] view plaincopyprint?
  1. @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)     
  2. public class User implements Serializable {  
  3. }  

在Dao层使用cache,代码如下

[java] view plaincopyprint?
  1. Session s = HibernateSessionFactory.getSession();  
  2. Criteria c = s.createCriteria(User.class);  
  3. c.setCacheable(true);//这句必须要有  
  4. System.out.println("第一次读取");  
  5. List<User> users = c.list();  
  6. System.out.println(users.size());  
  7. HibernateSessionFactory.closeSession();  
  8.   
  9. s = HibernateSessionFactory.getSession();  
  10. c = s.createCriteria(User.class);  
  11. c.setCacheable(true);//这句必须要有  
  12. System.out.println("第二次读取");  
  13. users = c.list();  
  14. System.out.println(users.size());  
  15. HibernateSessionFactory.closeSession();  

你会发现第二次查询没有打印sql语句,而是直接使用缓存中的对象。


如果你的Hibernate和Spring整合在一起,那么你可以用HibernateTemplate来设置cache

[java] view plaincopyprint?
  1. getHibernateTemplate().setCacheQueries(true);  
  2. return getHibernateTemplate().find("from User");  

当你整合Spring时,如果你的HibernateTemplate模板配置在Spring的Ioc容器中,那么你可以这样启用query cache

[html] view plaincopyprint?
  1. <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">  
  2.     <property name="sessionFactory">  
  3.        <ref bean="sessionFactory" />  
  4.     </property>  
  5.     <property name="cacheQueries">  
  6.        <value>true</value>  
  7.     </property>  
  8. </bean>  

此后,你在dao模块中注入sessionFactory的地方都注入hibernateTemplate即可。

 

以上讲到的都是Spring和Hibernate的配置,下面主要结合上面使用的ehcache,来完成ehcache.xml的配置。如果你没有配置ehcache,默认情况下使用defaultCache的配置。

[html] view plaincopyprint?
  1. <cache name="com.hoo.hibernate.entity.User" maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="300" timeToLiveSeconds="600" overflowToDisk="true" />  
  2. <!--  
  3. hbm文件查找cache方法名的策略:如果不指定hbm文件中的region="ehcache.xml中的name的属性值",则使用name名为com.hoo.hibernate.entity.User的cache,如果不存在与类名匹配的cache名称,则用 defaultCache。  
  4. 如果User包含set集合,则需要另行指定其cache  
  5. 例如User包含citySet集合,则需要  
  6. 添加如下配置到ehcache.xml中  
  7. -->  
  8. <cache name="com.hoo.hibernate.entity.citySet"  
  9. maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="300"  
  10. timeToLiveSeconds="600" overflowToDisk="true" />  

如果你使用了Hibernate的查询缓存,需要在ehcache.xml中加入下面的配置

[html] view plaincopyprint?
  1. <cache name="org.hibernate.cache.UpdateTimestampsCache"  
  2.     maxElementsInMemory="5000"   
  3.     eternal="true"   
  4.     overflowToDisk="true" />  
  5. <cache name="org.hibernate.cache.StandardQueryCache"  
  6.     maxElementsInMemory="10000"   
  7.     eternal="false"   
  8.     timeToLiveSeconds="120"  
  9.     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中,所以查询缓存通常会和二级缓存一起使用。


0 0
原创粉丝点击