---
title: "ehcache"
author: "weitinting"
date: "2015-04-08T22:26:16Z"
tags: []
categories: ["企业架构"]
slug: "ehcache"
draft: false
lastmod: "2015-04-08T22:26:16Z"
id: 2200412
url: "https://weitinting.iteye.com/blog/2200412"
---

**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文件，内容如下：  
        &lt;?xml version="1.0" encoding="UTF-8"?&gt;  
        &lt;ehcache&gt;   　  
            &lt;diskStore path="java.io.tmpdir" /&gt;  
          &lt;defaultCache maxElementsInMemory="5"&lt;!--缓存可以存储的总记录量--&gt;  
            eternal="false"&lt;!--缓存是否永远不销毁--&gt;  
            overflowToDisk="true"&lt;!--当缓存中的数据达到最大值时，是否把缓存数据写入磁盘--&gt;  
            timeToIdleSeconds="15"&lt;!--当缓存闲置时间超过该值，则缓存自动销毁--&gt;  
                timeToLiveSeconds="120"&lt;!--缓存创建之后，到达该缓存自动销毁--&gt;  
          /&gt;  
        &lt;/ehcache&gt;  
    4.2在Hibernate.cfg.xml中的mapping标签上面加以下内容：  
        &lt;property name="show\_sql"&gt;true&lt;/property&gt;  
        &lt;property name="hibernate.cache.provider\_class"&gt;org.hibernate.cache.EhCacheProvider&lt;/property&gt;  
        &lt;property name="hibernate.cache.use\_query\_cache"&gt;true&lt;/property&gt;  
    4.3在要缓存的bean的hbm.xml文件中的class标签下加入以下内容：  
       &lt;cache usage="read-only" /&gt;&lt;!--也可读写--&gt;  
    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**](http://ehcache.sourceforge.net/)，hibernate3.2必须要ehcache1.2以上才能支持。可以修改log4j配置文件log4j.logger.net.sf.hibernate.cache=debug查看日志

1.在类路径上ehcache.xml：

> &lt;ehcache&gt;
> 
>      &lt;!-- Sets the path to the directory where cache .data files are created.
> 
>           If the path is a Java System Property it is replaced by  
>           its value in the running VM.
> 
>           The following properties are translated:  
>           user.home - User's home directory  
>           user.dir - User's current working directory  
>           java.io.tmpdir - Default temp file path --&gt;  
>      &lt;diskStore path="java.io.tmpdir"/&gt;
> 
>      &lt;!--Default Cache configuration. These will applied to caches programmatically created through  
>          the CacheManager.
> 
>          The following attributes are required:
> 
>          maxElementsInMemory             - Sets the maximum number of objects that will be created in memory  
>          eternal                         - Sets whether elements are eternal. If eternal,   timeouts are ignored and the  
>                                           element is never expired.  
>          overflowToDisk                  - Sets whether elements can overflow to disk when the in-memory cache  
>                                           has reached the maxInMemory limit.
> 
>          The following attributes are optional:  
>          timeToIdleSeconds               - Sets the time to idle for an element before it expires.  
>                                           i.e. The maximum amount of time between accesses before an element expires  
>                                           Is only used if the element is not eternal.  
>                                           Optional attribute. A value of 0 means that an Element can idle for infinity.  
>                                           The default value is 0.  
>          timeToLiveSeconds               - Sets the time to live for an element before it expires.  
>                                           i.e. The maximum time between creation time and when an element expires.  
>                                           Is only used if the element is not eternal.  
>                                           Optional attribute. A value of 0 means that and Element can live for infinity.  
>                                           The default value is 0.  
>          diskPersistent                  - Whether the disk store persists between restarts of the Virtual Machine.  
>                                           The default value is false.  
>          diskExpiryThreadIntervalSeconds- The number of seconds between runs of the disk expiry thread. The default value  
>                                           is 120 seconds.  
>          --&gt;
> 
>      &lt;defaultCache  
>          maxElementsInMemory="10000"  
>          eternal="false"  
>          overflowToDisk="true"  
>          timeToIdleSeconds="120"  
>          timeToLiveSeconds="120"  
>          diskPersistent="false"  
>          diskExpiryThreadIntervalSeconds="120"/&gt;  
>           
>      &lt;!-- See http://ehcache.sourceforge.net/documentation/#mozTocId258426 for how to configure caching for your objects --&gt;  
> &lt;/ehcache&gt;

2.applicationContext-hibernate.xml里Hibernate SessionFactory配置：

> &lt;!-- Hibernate SessionFactory --&gt;  
>      &lt;bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"&gt;  
>          &lt;property name="dataSource" ref="dataSource"/&gt;  
>          &lt;property name="configLocation"&gt;&lt;value&gt;classpath:hibernate.cfg.xml&lt;/value&gt;&lt;/property&gt;  
>          &lt;!-- The property below is commented out b/c it doesn't work when run via  
>               Ant in Eclipse.   It works fine for individual JUnit tests and in IDEA ??  
>          &lt;property name="mappingJarLocations"&gt;  
>              &lt;list&gt;&lt;value&gt;file:dist/appfuse-dao.jar&lt;/value&gt;&lt;/list&gt;  
>          &lt;/property&gt;  
>          --&gt;  
>          &lt;property name="hibernateProperties"&gt;  
>              &lt;props&gt;  
>                  &lt;prop key="hibernate.dialect"&gt;@HIBERNATE-DIALECT@&lt;/prop&gt;  
>                  &lt;!--&lt;prop key="hibernate.show\_sql"&gt;true&lt;/prop&gt;--&gt;  
>                  &lt;prop key="hibernate.max\_fetch\_depth"&gt;3&lt;/prop&gt;  
>                  &lt;prop key="hibernate.hibernate.use\_outer\_join"&gt;true&lt;/prop&gt;  
>                  &lt;prop key="hibernate.jdbc.batch\_size"&gt;10&lt;/prop&gt;  
>                  **&lt;prop key="hibernate.cache.use\_query\_cache"&gt;true&lt;/prop&gt;**  
>                  **&lt;prop key="hibernate.cache.use\_second\_level\_cache"&gt;true&lt;/prop&gt;**  
>                  **&lt;prop key="hibernate.cache.provider\_class"&gt;org.hibernate.cache.EhCacheProvider&lt;/prop&gt;**  
>                  &lt;!--  
>                  &lt;prop key="hibernate.use\_sql\_comments"&gt;false&lt;/prop&gt;  
>                  --&gt;  
>                  &lt;!-- Create/update the database tables automatically when the JVM starts up  
>                  &lt;prop key="hibernate.hbm2ddl.auto"&gt;update&lt;/prop&gt; --&gt;  
>                  &lt;!-- Turn batching off for better error messages under PostgreSQL  
>                  &lt;prop key="hibernate.jdbc.batch\_size"&gt;0&lt;/prop&gt; --&gt;  
>              &lt;/props&gt;  
>          &lt;/property&gt;  
>          &lt;property name="entityInterceptor"&gt;  
>             &lt;ref local="auditLogInterceptor"/&gt;  
>          &lt;/property&gt;  
>      &lt;/bean&gt;  
> 说明：如果不设置“查询缓存”，那么hibernate只会缓存使用load()方法获得的单个持久化对象，如果想缓存使用findall()、 list()、Iterator()、createCriteria()、createQuery()等方法获得的数据结果集的话，就需要设置 hibernate.cache.use\_query\_cache true 才行

3.model类里采用Xdoclet生成\*.hbm.xml里的cache xml标签，即&lt;cache usage="read-only"/&gt;

> /\**  
> * @hibernate.class table="WF\_WORKITEM\_HIS"  
> * @hibernate.cache usage="read-write"  
> *   
> \*/

4.对于"query cache"，需要在程序里编码：

         getHibernateTemplate().setCacheQueries(true);  
         return getHibernateTemplate().find(hql);

 

 

**使用spring和hibernate配置ehcache和query cache**

 

1、applicationContext.xml  
&lt;prop key="hibernate.cache.provider\_class"&gt;org.hibernate.cache.EhCacheProvider&lt;/prop&gt;  
&lt;prop key="hibernate.cache.use\_query\_cache"&gt;true&lt;/prop&gt;

这两句加到hibernateProperties中  
&lt;bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"&gt;  
&lt;property name="sessionFactory"&gt;  
   &lt;ref bean="sessionFactory" /&gt;  
&lt;/property&gt;  
&lt;property name="cacheQueries"&gt;  
   &lt;value&gt;true&lt;/value&gt;  
&lt;/property&gt;  
&lt;/bean&gt;

添加此bean到applicationcontext.xml中。在各个DAO的bean中，更改如下  
&lt;property name="sessionFactory"&gt;  
&lt;ref bean="sessionFactory" /&gt;  
&lt;/property&gt;  
改为  
&lt;property name="hibernateTemplate"&gt;  
&lt;ref bean="hibernateTemplate" /&gt;  
&lt;/property&gt;

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

3、pojo与ehcache.xml的配置关系  
以com.ce.ceblog.pojos.CeblogJournal为例子  
在CeblogJournal.hbm.xml中配置：  
&lt;class name="CeblogJournal" table="CEBLOG\_JOURNAL" lazy="false"&gt;  
&lt;cache usage="read-write" region="ehcache.xml中的name的属性值"/&gt;  
注意：这一句需要紧跟在class标签下面，其他位置无效。

Ehcache.xml文件主体如下  
&lt;defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="1" timeToLiveSeconds="1" overflowToDisk="true" /&gt;  
&lt;cache name="com.ce.ceblog.pojos.CeblogJournal" maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="300" timeToLiveSeconds="600" overflowToDisk="true" /&gt;  
hbm文件查找cache方法名的策 略：如果不指定hbm文件中的region="ehcache.xml中的name的属性值"，则使用name名为 com.ce.ceblog.pojos.CeblogJournal的cache，如果不存在与类名匹配的cache名称，则用 defaultCache。  
如果CeblogJournal包含set集合，则需要另行指定其cache  
例如CeblogJournal包含ceblogReplySet集合，则需要  
添加如下配置到ehcache.xml中  
&lt;cache name="com.ce.ceblog.pojos.CeblogJournal.ceblogReplySet"  
maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="300"  
timeToLiveSeconds="600" overflowToDisk="true" /&gt;

另，针对查询缓存的配置如下：  
&lt;cache name="org.hibernate.cache.UpdateTimestampsCache"  
maxElementsInMemory="5000"  
eternal="true"  
overflowToDisk="true"/&gt;  
&lt;cache name="org.hibernate.cache.StandardQueryCache"  
maxElementsInMemory="10000"  
eternal="false"  
timeToLiveSeconds="120"  
overflowToDisk="true"/&gt;

4、选择缓存策略依据：  
&lt;cache usage="transactional|read-write|nonstrict-read-write|read-only" /&gt;  
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语句是正常的，因为query cache设置为true将会创建两个缓存区域：一个用于保存查询结果集 (org.hibernate.cache.StandardQueryCache)； 另一个则用于保存最近查询的一系列表的时间戳(org.hibernate.cache.UpdateTimestampsCache)。请注意：在查询 缓存中，它并不缓存结果集中所包含的实体的确切状态；它只缓存这些实体的标识符属性的值、以及各值类型的结果。需要将打印sql语句与最近的cache内 容相比较，将不同之处修改到cache中，所以查询缓存通常会和二级缓存一起使用。