hibernate的一級緩衝、二級緩衝、查詢快取

來源:互聯網
上載者:User

一級緩衝與二級緩衝

a.一級緩衝(session級的緩衝):在一個session中load同一個對象2次,load時,hibernate首先在session緩衝中尋找對象,如果沒找到就到資料庫中去load。因此,在同一個session中load一個對象2次,只會發出一條sql語句。

b.二級緩衝即sessionfactory層級的緩衝,hibernate支援多種二級緩衝,常用ehcache

-------------------------------------------------------------------------------------------------------------------------

二級緩衝的應用步驟:

1.在hibernate.cfg.xml中加上:

 <property name="cache.use_second_level_cache">true</property>
<property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<property name="cache.use_query_cache">true</property>

在applicationContext.xml中的Hibernate SessionFactory配置:

<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.OracleDialect
</prop>
<prop key="hibernate.show_sql">false</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.cache.use_query_cache">true</prop>
 
<!--  
<prop key="hibernate.hbm2ddl.auto">update</prop>
-->
</props>
</property>

2.把hibernate包裡的ehcache.xml檔案放到src目錄下

<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 for defaultCache:        maxInMemory       - 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.        timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used                            if the element is not eternal. Idle time is now - last accessed time        timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used                            if the element is not eternal. TTL is now - creation time        overflowToDisk    - Sets whether elements can overflow to disk when the in-memory cache                            has reached the maxInMemory limit.        -->    <defaultCache        maxElementsInMemory="10000"        eternal="false"        timeToIdleSeconds="120"        timeToLiveSeconds="1200"        overflowToDisk="true"        />    <!--Predefined caches.  Add your cache configuration settings here.        If you do not have a configuration for your cache a WARNING will be issued when the        CacheManager starts        The following attributes are required for defaultCache:        name              - Sets the name of the cache. This is used to identify the cache. It must be unique.        maxInMemory       - 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.        timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used                            if the element is not eternal. Idle time is now - last accessed time        timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used                            if the element is not eternal. TTL is now - creation time        overflowToDisk    - Sets whether elements can overflow to disk when the in-memory cache                            has reached the maxInMemory limit.        -->    <!-- Sample cache named sampleCache1        This cache contains a maximum in memory of 10000 elements, and will expire        an element if it is idle for more than 5 minutes and lives for more than        10 minutes.        If there are more than 10000 elements it will overflow to the        disk cache, which in this configuration will go to wherever java.io.tmp is        defined on your system. On a standard Linux system this will be /tmp"        -->    <cache name="sampleCache1"        maxElementsInMemory="10000"        eternal="false"        timeToIdleSeconds="300"        timeToLiveSeconds="600"        overflowToDisk="true"                />    <!-- Sample cache named sampleCache2        This cache contains 1000 elements. Elements will always be held in memory.        They are not expired. -->    <cache name="sampleCache2"        maxElementsInMemory="1000"        eternal="true"        timeToIdleSeconds="0"        timeToLiveSeconds="0"        overflowToDisk="false"        /> -->    <!-- Place configuration for your caches following --></ehcache>

 

 i.必須要有的屬性:

    name: cache的名字,用來識別不同的cache,必須惟一。

   maxElementsInMemory: 記憶體管理的緩衝元素數量最大限值。

   maxElementsOnDisk: 硬碟管理的緩衝元素數量最大限值。預設值為0,就是沒有限制。

   eternal: 設定元素是否持久話。若設為true,則緩衝元素不會到期。

   overflowToDisk: 設定是否在記憶體填滿的時候把資料轉到磁碟上。

ii.下面是一些可選屬性:

    timeToIdleSeconds:設定元素在到期前空閑狀態的時間,只對非持久性緩衝對象有效。預設值為0,值為0意味著元素可以閑置至無限長時間。

   timeToLiveSeconds: 設定元素從建立到到期的時間。其他與timeToIdleSeconds類似。

    diskPersistent: 設定在虛擬機器重啟時是否進行磁碟儲存,預設為false.(我的直覺,對於安全小型應用,宜設為true)。

   diskExpiryThreadIntervalSeconds: 訪問磁碟線程啟用時間。

   diskSpoolBufferSizeMB: 存入磁碟時的緩衝區大小,預設30MB,每個緩衝都有自己的緩衝區。

   memoryStoreEvictionPolicy: 元素逐出緩衝規則。共有三種,Recently Used (LRU)最近最少使用,為預設。 First In First Out (FIFO),先進先出。Less Frequently Used(specified as LFU)最少使用。
上面的ehcache.xml檔案除了defaultCache緩衝外,還有sampleCache1和sampleCache2,在給實體設定緩衝的時候可以指定緩衝
3.@ecache註解,如下例子:

@Entity@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)public class Permission{private int id;private String name;@Id@GeneratedValuepublic int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}}
 
 

4.加入ehcache-1.5.0.jar包,在hibernate-distribution-3.6.0.Final\lib\optional\ehcache目錄下     注意:ehcache使用了commons-logging的包,也要加上二級緩衝總結: 

a.load和iterator預設使用二級緩衝

b.list預設往二級緩衝加資料,但是查詢的時候不使用

----------------------------------------------------------------------------------------------------
查詢快取:

如果要query用二級緩衝,需開啟查詢快取:

<property name="hibernate.cache.use_query_cache">true</property>
注意:a.查詢快取依賴於二級緩衝,必須開啟二級緩衝
            b.查詢快取在查詢條件一樣的時候才會起作用,如果條件不一樣則不起作用

            c.調用Query的setCachable(true)方法指明使用二級緩衝

源碼eg:

Session session = sf.openSession();session.beginTransaction();List<Category> categories = (List<Category>)session.createQuery("from Category").setCacheable(true).list();session.getTransaction().commit();session.close();Session session2 = sf.openSession();session2.beginTransaction();List<Category> categories2 = (List<Category>)session2.createQuery("from Category").setCacheable(true).list();session2.getTransaction().commit();session2.close();

緩衝演算法:

 1.LRU:least Recently Used 最近最少用到的

  2.LFU:least Frequently Used(命中率高低)

  3.FIFO:First  In First Out  類似數組,先進先出

ehcache對這三種演算法都支援,我們可以在ehcache.xml中增加:

 <defaultCache        maxElementsInMemory="10000"  <!--緩衝儲存的最大數量 -->        eternal="false"  <!--設定元素是否持久話。若設為true,則緩衝元素不會到期 -->        timeToIdleSeconds="120" <!--設定元素在到期前空閑狀態的時間,只對非持久性緩衝對象有效。預設值為0,值為0意味著元素可以閑置至無限長時間 -->        timeToLiveSeconds="1200" <!--設定元素從建立到到期的時間,其他與timeToIdleSeconds類似 -->        overflowToDisk="true" <!--設定是否在記憶體填滿的時候把資料轉到磁碟上 -->
        memoryStoreEvictionPolicy=“LRU”

        />

好文章:http://blog.csdn.net/nuoyan666/article/details/6577732

http://www.ibm.com/developerworks/cn/java/j-lo-ehcache/index.html(叢集,有時間在看)

http://hi.baidu.com/yinaddress/blog/item/f333f0d9af38f93e33fa1c28.html

http://hi.baidu.com/liang125353769/blog/item/a5ec79eb571b44cbd439c92d.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.