ehcache

來自http://www.blogjava.net/i369/articles/219407.html

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:

<ehcache>

     <!-- 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 -->
     <diskStore path="java.io.tmpdir"/>


     <!--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.
         -->

     <defaultCache
         maxElementsInMemory="10000"
         eternal="false"
         overflowToDisk="true"
         timeToIdleSeconds="120"
         timeToLiveSeconds="120"
         diskPersistent="false"
         diskExpiryThreadIntervalSeconds="120"/>
        
     <!-- See http://ehcache.sourceforge.net/documentation/#mozTocId258426 for how to configure caching for your objects -->
</ehcache>

2.applicationContext-hibernate.xml裏Hibernate 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>
         <!-- 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 ??
         <property name="mappingJarLocations">
             <list><value>file:dist/appfuse-dao.jar</value></list>
         </property>
         -->
         <property name="hibernateProperties">
             <props>
                 <prop key="hibernate.dialect">@HIBERNATE-DIALECT@</prop>
                 <!--<prop key="hibernate.show_sql">true</prop>-->
                 <prop key="hibernate.max_fetch_depth">3</prop>
                 <prop key="hibernate.hibernate.use_outer_join">true</prop>
                 <prop key="hibernate.jdbc.batch_size">10</prop>
                 <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>
                 <!--
                 <prop key="hibernate.use_sql_comments">false</prop>
                 -->
                 <!-- Create/update the database tables automatically when the JVM starts up
                 <prop key="hibernate.hbm2ddl.auto">update</prop> -->
                 <!-- Turn batching off for better error messages under PostgreSQL
                 <prop key="hibernate.jdbc.batch_size">0</prop> -->
             </props>
         </property>
         <property name="entityInterceptor">
            <ref local="auditLogInterceptor"/>
         </property>
     </bean>
說明:如果不設置“查詢緩存”,那麼hibernate只會緩存使用load()方法獲得的單個持久化對象,如果想緩存使用findall()、 list()、Iterator()、createCriteria()、createQuery()等方法獲得的數據結果集的話,就需要設置 hibernate.cache.use_query_cache true 才行

3.model類裏採用Xdoclet生成*.hbm.xml裏的cache xml標籤,即<cache usage="read-only"/>

/**
* @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
<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>

這兩句加到hibernateProperties中
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory">
   <ref bean="sessionFactory" />
</property>
<property name="cacheQueries">
   <value>true</value>
</property>
</bean>

添加此bean到applicationcontext.xml中。在各個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.ce.ceblog.pojos.CeblogJournal爲例子
在CeblogJournal.hbm.xml中配置:
<class name="CeblogJournal" table="CEBLOG_JOURNAL" lazy="false">
<cache usage="read-write" region="ehcache.xml中的name的屬性值"/>
注意:這一句需要緊跟在class標籤下面,其他位置無效。

Ehcache.xml文件主體如下
<defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="1" timeToLiveSeconds="1" overflowToDisk="true" />
<cache name="com.ce.ceblog.pojos.CeblogJournal" maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="300" timeToLiveSeconds="600" overflowToDisk="true" />
hbm文件查找cache方法名的策 略:如果不指定hbm文件中的region="ehcache.xml中的name的屬性值",則使用name名爲 com.ce.ceblog.pojos.CeblogJournal的cache,如果不存在與類名匹配的cache名稱,則用 defaultCache。
如果CeblogJournal包含set集合,則需要另行指定其cache
例如CeblogJournal包含ceblogReplySet集合,則需要
添加如下配置到ehcache.xml中
<cache name="com.ce.ceblog.pojos.CeblogJournal.ceblogReplySet"
maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="300"
timeToLiveSeconds="600" overflowToDisk="true" />

另,針對查詢緩存的配置如下:
<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"/>

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語句是正常的,因爲query cache設置爲true將會創建兩個緩存區域:一個用於保存查詢結果集 (org.hibernate.cache.StandardQueryCache); 另一個則用於保存最近查詢的一系列表的時間戳(org.hibernate.cache.UpdateTimestampsCache)。請注意:在查詢 緩存中,它並不緩存結果集中所包含的實體的確切狀態;它只緩存這些實體的標識符屬性的值、以及各值類型的結果。需要將打印sql語句與最近的cache內 容相比較,將不同之處修改到cache中,所以查詢緩存通常會和二級緩存一起使用。
發佈了15 篇原創文章 · 獲贊 0 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章