码迷,mamicode.com
首页 > 编程语言 > 详细

在Spring、Hibernate中使用Ehcache缓存(2)

时间:2015-03-10 13:32:10      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:

这里将介绍在Hibernate中使用查询缓存、一级缓存、二级缓存,整合Spring在HibernateTemplate中使用查询缓存。,这里是hibernate3,使用hibernate4类似,不过不用hibernatetemplate,
直接
        Query query = getSession().createQuery(hql);
        //开启二级缓存
        query.setCacheable(true);

 

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(序列化事务隔离级别)

SELECT @@tx_isolation查看

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中,所以查询缓存通常会和二级缓存一起使用。

 

在Spring、Hibernate中使用Ehcache缓存(2)

标签:

原文地址:http://www.cnblogs.com/crazylqy/p/4325566.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!