Hibernate性能优化之EHCache缓存 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倍。

前一篇http://www.blogjava.net/hoojo/archive/2012/07/12/382852.html介绍了Ehcache整合Spring缓存,使用页面、对象缓存;这里将介绍在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)  
  • read-only

  • nontrict read-write

  • read-write

   
EHCache  
  • read-only

  • nontrict read-write

  • read-write

   
OSCache  
  • read-only

  • nontrict read-write

  • read-write

   
SwarmCache  
  • read-only

  • nontrict read-write

   
JBoss Cache 1.x  
  • read-only

  • transactional

   
JBoss Cache 2.x  
  • read-only

  • transactional

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,添加以下内容

[html]  view plain  copy
 
  1.    <!-- 开启二级缓存,使用EhCache缓存 -->  
  2. <prop key="hibernate.cache.use_second_level_cache">true</prop>  
  3. <prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>  

          1-2)配置哪些实体类的对象需要存放到二级缓存,有两种方式

                    本案例中,以edu.po.Users用户对象为例子,对应的实体映射文件为Users.hbm.xml。

                   方式一,在hibernate.cfg.xml文件中配置

[html]  view plain  copy
 
  1. <!-- 要使用二级缓存的对象配置 -->  
  2.    <class-cache usage="read-write" class="edu.po.Users"/>    
  3. <!-- 缓存集合对象的例子 -->  
  4. <!-- <collection-cache usage="read-write" collection="cn.itcast.domain.Customer.orders"/> -->  

                   方式二,在hbm文件(实体映射文件)中配置

                   Users.hbm.xml,添加以下内容:

[html]  view plain  copy
 
  1. <cache usage="read-write"/>  

   2)集成了Spring框架之后,没有hibenate.cfg.mlx文件

           1-1)开启Hibernate缓存二级缓存功能

                    修改applicationContext.xml文件,在sessionFactory Bean中添加以下hibernateProperties,如下:

[html]  view plain  copy
 
  1. <bean id="sessionFactory"  
  2.     class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">  
  3.     ......  
  4.     <property name="hibernateProperties">  
  5.         <props>  
  6.            ......  
  7.            <!-- 开启二级缓存,使用EhCache缓存 -->  
  8.            <prop key="hibernate.cache.use_second_level_cache">true</prop>  
  9.            <prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>  
  10.            ......  
  11.         </props>  
  12.     </property>  
  13.     <property name="mappingResources">  
  14.         <list>  
  15.            <value>edu/po/Users.hbm.xml</value>  
  16.            <value>edu/po/TLog.hbm.xml</value>  
  17.         </list>  
  18.     </property>  
  19. </bean>  


          1-2)配置哪些实体类的对象需要存放到二级缓存

                   本案例中,以edu.po.Users用户对象为例子,对应的实体映射文件为Users.hbm.xml。

                   在hbm文件(实体映射文件)中配置

                   Users.hbm.xml,添加以下内容:

[html]  view plain  copy
 
  1. <cache usage="read-write"/>  

4、配置ehcache.xml文件

      将ehcache.jar包中的ehcache-failsafe.xml 改名为 ehcache.xml 放入 src,因为hibernate默认找classpath*:ehcache.xml

      本案例,对<diskStore>和<defaultCache>进行修改,如下

[html]  view plain  copy
 
  1. <diskStore path="d:/EhCacheData"/>  
[html]  view plain  copy
 
  1. <!--   
  2.    maxElementsInMemory: 内存中最大对象数量 ,超过数量,数据会被缓存到硬盘  
  3.    eternal:缓存的对象是否有有效期(即是否永久存在)。如果为true,timeouts属性被忽略  
  4.    timeToIdleSeconds:缓存的对象在过期前的空闲时间,单位秒  
  5.    timeToLiveSeconds:存活时间,对象不管是否使用,到了时间回收,单位秒  
  6.    overflowToDisk:当内存中缓存对象数量达到 maxElementsInMemory 限制时,是否可以写到硬盘  
  7.    maxElementsOnDisk:硬盘缓存最大对象数量  
  8.    diskPersistent:在java虚拟机(JVM)重启或停掉的时候,是否持久化磁盘缓存,默认是false  
  9.    diskExpiryThreadIntervalSeconds:清除磁盘缓存中过期对象的监听线程的运行间隔,默认是120秒  
  10.    memoryStoreEvictionPolicy:当内存缓存的对象数量达到最大,有新的对象要加入的时候,  
  11.                                                                 移除缓存中对象的策略。默认是LRU,可选的有LFU和FIFO  
  12. -->  
  13. <defaultCache  
  14.         maxElementsInMemory="10000"   
  15.         eternal="false"  
  16.         timeToIdleSeconds="120"  
  17.         timeToLiveSeconds="120"  
  18.         overflowToDisk="true"  
  19.         diskPersistent="true"  
  20.         diskExpiryThreadIntervalSeconds="120"  
  21.         memoryStoreEvictionPolicy="LRU"  
  22.         />  

5、demo

SpringBeanUtils.java:

[java]  view plain  copy
 
  1. package utils;  
  2.   
  3. import org.apache.log4j.Logger;  
  4. import org.hibernate.SessionFactory;  
  5. import org.springframework.context.ApplicationContext;  
  6. import org.springframework.context.support.FileSystemXmlApplicationContext;  
  7.   
  8. /** 
  9.  * Title: SpringBeanUtils.java 
  10.  * Description: 获取Spring的Bean实例对象的工具类 
  11.  * @author yh.zeng 
  12.  * @date 2017-6-27 
  13.  */  
  14. public class SpringBeanUtils {  
  15.       
  16.     private static Logger logger = Logger.getLogger(SpringBeanUtils.class);  
  17.       
  18.     static String filePath ="WebRoot/WEB-INF/applicationContext.xml";  
  19.     static  ApplicationContext CONTEXT ;  
  20.     static{  
  21.         try{  
  22.             CONTEXT = new FileSystemXmlApplicationContext(filePath);  
  23.         }catch(Exception e){  
  24.             logger.error(StringUtils.getExceptionMessage(e));  
  25.         }  
  26.     }  
  27.       
  28.       
  29.     /** 
  30.      * 获取Bean 
  31.      * @param uniqueIdentifier Bean的唯一标识,可以是ID也可以是name 
  32.      * @return 
  33.      */  
  34.     public static Object getBean(String uniqueIdentifier){  
  35.         return CONTEXT.getBean(uniqueIdentifier);  
  36.     }  
  37.       
  38.     /** 
  39.      * 获取SessionFacotry对象 
  40.      * @param uniqueIdentifier  SessionFactory Bean的唯一标识,可以是ID也可以是name 
  41.      * @return 
  42.      */  
  43.     public static SessionFactory getSessionFactory(String uniqueIdentifier){  
  44.         return (SessionFactory) CONTEXT.getBean(uniqueIdentifier);  
  45.     }  
  46.   
  47.     public static String getFilePath() {  
  48.         return filePath;  
  49.     }  
  50.   
  51.     public static void setFilePath(String filePath) {  
  52.         SpringBeanUtils.filePath = filePath;  
  53.         CONTEXT = new FileSystemXmlApplicationContext(filePath);  
  54.     }  
  55.       
  56. }  

HibernateEhCacheTest.java:

注意:查询缓存和查看Cache(缓存)统计信息的功能,需要做另外配置,见博客Hibernate开启查询缓存Hibernate开启收集缓存统计信息

[java]  view plain  copy
 
  1. package edu.test;  
  2.   
  3. import java.sql.SQLException;  
  4. import org.hibernate.HibernateException;  
  5. import org.hibernate.Query;  
  6. import org.hibernate.Session;  
  7. import org.hibernate.SessionFactory;  
  8. import org.hibernate.stat.EntityStatistics;  
  9. import org.hibernate.stat.Statistics;  
  10. import org.springframework.orm.hibernate3.HibernateCallback;  
  11. import org.springframework.orm.hibernate3.HibernateTemplate;  
  12. import utils.SpringBeanUtils;  
  13. import edu.po.Users;  
  14.   
  15. /** 
  16.  * Title: HibernateEhCacheTest.java 
  17.  * Description: Hibernate二级缓存测试 
  18.  * @author yh.zeng 
  19.  * @date 2017-7-4 
  20.  */  
  21. public class HibernateEhCacheTest {  
  22.   
  23.     static SessionFactory  sessionFactory = SpringBeanUtils.getSessionFactory("sessionFactory");  
  24.       
  25.     public static void main(String args[]) {  
  26.           
  27.         //Session.get()方法支持二级缓存  
  28.         System.out.println("###############session.get()###############");  
  29.         Session session1 = sessionFactory.openSession();  
  30.         session1.beginTransaction();  
  31.         Users user1 = (Users)session1.get(Users.class, 6);  
  32.         System.out.println("用户名:" + user1.getUsername());  
  33.         session1.getTransaction().commit();  
  34.         session1.close();  
  35.   
  36.         Session session2 = sessionFactory.openSession();  
  37.         session2.beginTransaction();  
  38.         Users user2 = (Users)session2.get(Users.class, 6);  
  39.         System.out.println("用户名:" + user2.getUsername());  
  40.         session2.getTransaction().commit();  
  41.         session2.close();  
  42.           
  43.         //Query.list()方法支持查询缓存  
  44.         System.out.println("###############Query.list()###############");  
  45.         Session session3 = sessionFactory.openSession();  
  46.         session3.beginTransaction();  
  47.         Query query = session3.createQuery("from Users where id = :id");  
  48.         query.setParameter("id", 6);  
  49.         query.setCacheable(true); //启用查询缓存  
  50.         Users user3 = (Users)query.list().get(0);  
  51.         System.out.println("用户名:" + user3.getUsername());  
  52.         session3.getTransaction().commit();  
  53.         session3.close();  
  54.           
  55.           
  56.         Session session4 = sessionFactory.openSession();  
  57.         session4.beginTransaction();  
  58.         Query query2 = session4.createQuery("from Users where id = :id");  
  59.         query2.setParameter("id", 6);  
  60.         query2.setCacheable(true); //启用查询缓存  
  61.         Users user4 = (Users)query2.list().get(0);  
  62.         System.out.println("用户名:" + user4.getUsername());  
  63.         session4.getTransaction().commit();  
  64.         session4.close();  
  65.           
  66.         //Query.iterate()方法不支持查询缓存  
  67.         System.out.println("###############Query.iterate()###############");  
  68.         Session session5 = sessionFactory.openSession();  
  69.         session5.beginTransaction();  
  70.         Query query3 = session5.createQuery("from Users where id = :id");  
  71.         query3.setParameter("id", 6);  
  72.         query3.setCacheable(true); //启用查询缓存  
  73.         Users user5 = (Users)query3.iterate().next();  
  74.         System.out.println("用户名:" + user5.getUsername());  
  75.         session5.getTransaction().commit();  
  76.         session5.close();  
  77.           
  78.         Session session6 = sessionFactory.openSession();  
  79.         session6.beginTransaction();  
  80.         Query query4 = session6.createQuery("from Users where id = :id");  
  81.         query4.setParameter("id", 6);  
  82.         query4.setCacheable(true); //启用查询缓存  
  83.         Users user6 = (Users)query4.iterate().next();  
  84.         System.out.println("用户名:" + user6.getUsername());  
  85.         session6.getTransaction().commit();  
  86.         session6.close();  
  87.           
  88.         //Session.load()方法支持二级缓存  
  89.         System.out.println("###############Session.load()###############");  
  90.         Session session7 = sessionFactory.openSession();  
  91.         session7.beginTransaction();  
  92.         Users user7 = (Users)session7.load(Users.class, 6);  
  93.         System.out.println("用户名:" + user7.getUsername());  
  94.         session7.getTransaction().commit();  
  95.           
  96.         Session session8 = sessionFactory.openSession();  
  97.         session8.beginTransaction();  
  98.         Users user8 = (Users)session8.load(Users.class, 6);  
  99.         System.out.println("用户名:" + user8.getUsername());  
  100.         session8.getTransaction().commit();  
  101.           
  102.         //HibernateTemplate.find支持查询缓存  
  103.         System.out.println("###############HibernateTemplate.find()###############");  
  104.         HibernateTemplate hibernateTemplate = new HibernateTemplate(sessionFactory);  
  105.         hibernateTemplate.setCacheQueries(true); //开启查询缓存  
  106.         Users user9 = (Users)hibernateTemplate.find("from Users where id = ?",6).get(0);  
  107.         System.out.println("用户名:" + user9.getUsername());  
  108.           
  109.         HibernateTemplate hibernateTemplate2 = new HibernateTemplate(sessionFactory);  
  110.         hibernateTemplate2.setCacheQueries(true); //开启查询缓存  
  111.         Users user10 = (Users)hibernateTemplate2.find("from Users where id = ?",6).get(0);  
  112.         System.out.println("用户名:" + user10.getUsername());  
  113.           
  114.         //HibernateTemplate.execute支持查询缓存  
  115.         System.out.println("###############HibernateTemplate.execute()###############");  
  116.         HibernateTemplate hibernateTemplate3 = new HibernateTemplate(sessionFactory);  
  117.         hibernateTemplate3.setCacheQueries(true); //开启查询缓存  
  118.         Users user11 = hibernateTemplate3.execute(new HibernateCallback<Users>() {  
  119.             @Override  
  120.             public Users doInHibernate(Session session) throws HibernateException,  
  121.                     SQLException {  
  122.                 // TODO Auto-generated method stub  
  123.                 Query query = session.createQuery("from Users where id = :id");  
  124.                 query.setParameter("id", 6);  
  125.                 return (Users)query.list().get(0);  
  126.             }  
  127.         });  
  128.         System.out.println("用户名:" + user11.getUsername());  
  129.           
  130.         HibernateTemplate hibernateTemplate4 = new HibernateTemplate(sessionFactory);  
  131.         hibernateTemplate4.setCacheQueries(true); //开启查询缓存  
  132.         Users user12 = hibernateTemplate4.execute(new HibernateCallback<Users>() {  
  133.             @Override  
  134.             public Users doInHibernate(Session session) throws HibernateException,  
  135.                     SQLException {  
  136.                 // TODO Auto-generated method stub  
  137.                 Query query = session.createQuery("from Users where id = :id");  
  138.                 query.setParameter("id", 6);  
  139.                 return (Users)query.list().get(0);  
  140.             }  
  141.         });  
  142.         System.out.println("用户名:" + user12.getUsername());  
  143.           
  144.         //Cache统计统计信息  
  145.         Statistics statistics= sessionFactory.getStatistics();  
  146.         System.out.println(statistics);  
  147.         System.out.println("放入"+statistics.getSecondLevelCachePutCount());  
  148.         System.out.println("命中"+statistics.getSecondLevelCacheHitCount());  
  149.         System.out.println("错过"+statistics.getSecondLevelCacheMissCount());  
  150.         //详细的Cache统计信息  
  151.         for (int i = 0; i < statistics.getEntityNames().length; i++) {  
  152.             String entityName = statistics.getEntityNames()[i];  
  153.             EntityStatistics entityStatistics = statistics.getEntityStatistics(entityName);  
  154.             StringBuilder cacheOperator = new StringBuilder();  
  155.             cacheOperator.append("CategoryName:" ).append(entityStatistics.getCategoryName())  
  156.                          .append(",DeleteCount:").append(entityStatistics.getDeleteCount())  
  157.                          .append(",FetchCount:").append(entityStatistics.getFetchCount())  
  158.                          .append(",InsertCount:").append(entityStatistics.getInsertCount())  
  159.                          .append(",LoadCount:").append(entityStatistics.getLoadCount())                        
  160.                          .append(",OptimisticFailureCount:").append(entityStatistics.getOptimisticFailureCount())     
  161.                          .append(",UpdateCount:").append(entityStatistics.getUpdateCount());                           
  162.             System.out.println(cacheOperator.toString());  
  163.         }  
  164.     }  
  165. }  


 

项目demo:  https://github.com/zengyh/SSHWebProject.git
 

    

参考:Hibernate性能优化之EHCache缓存

参考:Hibernate二级缓存,使用Ehache缓存框架

参考:在Spring、Hibernate中使用Ehcache缓存

猜你喜欢

转载自www.cnblogs.com/aspirant/p/9098728.html