什麼是二級緩存
二級緩存在Hibernate中對應爲SessionFactory範圍的緩存,通常來講sessionfactory的生命週期和應用的生命週期相同,所以可以看成是進程緩存或集羣緩存。
二級緩存由SessionFactory創建所有Session對象共享使用,二級緩存是使用第三方的緩存插件實現的。
不適合加載到二級緩存中的情況
1.經常被修改的數據
2.絕對不允許出現並訪問的數據
3.與其他應用共享的數據
適合加載到二級緩存中的數據:
1.數據更新頻率低
2.允許偶爾初見併發問題的非重要數據
3.不會被併發訪問的數據
4.常量數據
5.不會被第三方修改的數據
因爲二級緩存需要第三方插件,所以接下來配置第三方插件
1)常用二級緩存插件
1.EhCahe:可作爲進程範圍的緩存,存放數據的物理介質可以是內存或硬盤。org.hibernate.cache.EhCacheProvider
2.OSCache:可作爲進程範圍的緩存,存放數據的物理介質可以是內存或硬盤,提供了豐富的緩存數據過期策略。
org.hibernate.cache.OSCacheProvider
3.SwarmCache:可作爲羣集範圍內的緩存,但不支持Hibernate的查詢緩存。org.hibernate.cache.SwarmCacheProvider
4.JBossCache:可作爲羣集範圍內的緩存,支持事物型併發訪問。org.hibernate.cache.TreeCacheProvider
2)配置EhCahe插件
1.將架包導入到工程
2.配置hibernate.cfg.xml文件
設置屬性開啓二級緩存:
<span style="font-family:SimSun;font-size:14px;"><property name="hibernate.cache.use_second_level_cache">true</property></span>
指定緩存產品提供商:<span style="font-family:SimSun;font-size:14px;"><property name="hibernate.cache.provider_class">
org.hibernate.cache.EhCacheProvider
</property></span>
3.配置ehcache.xml文件<span style="font-family:SimSun;font-size:14px;"><ehcache>
<diskStore path="java.io.tmpdir"/>
<!--
maxElementsInMemory - 設置緩存最大數目
eternal - 設置緩存中的數據是否失效true爲永不過期。
timeToIdleSeconds - 緩存數據存在時間,單位是秒
timeToLiveSeconds - 指定緩存時間到了以後在過多長時間釋放緩存數據,單位是秒
overflowToDisk - 是否將一處的對象寫到基於硬盤的緩存中
-->
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
/>
</ehcache></span>
4.指定可以使用二級緩存的持久化類(1).第一種:在對應的*.hbm.xml文件中填寫
<span style="font-family:SimSun;font-size:14px;"><class>
<Cache usage="" region="" include=""/>
.....
</class></span>
(2).第二種:在hibernate.cgf.xml中配置<span style="font-family:SimSun;font-size:14px;"><class-cache class="" usage="read-write"/> class屬性爲包名加類名</span>
<cache>屬性:usage屬性是必須的,指定併發訪問策略,取值爲transactional(事務緩存)、read-write(讀寫緩存)、nonstrict-read-write(非嚴格讀寫緩存)、read-only(只讀緩存)。
region屬性可選,默認爲類或者集合的名稱。就是你在ehcache.xml文件中設置緩存名字
include屬性可選,取值爲non-lazy(當緩存一個對象時,不會緩存它的映射爲延遲加載的屬性)、all,默認爲all
二級緩存的管理:
使用SessiongFactory對象獲取Cache對象,sessionFactory.getCache();通過Cache來管理二級緩存。