Spring 整合 Hibernate 時啓用二級緩存

寫在前面:
  1. 本例使用 Hibernate3 + Spring3;
  2. 本例的查詢使用了 HibernateTemplate;

1. 導入 ehcache-x.x.x.jar 包;

2. 在 applicationContext.xml 文件中找到 sessionFactory 相應的配置信息並在設置 hibernateProperties 中添加如下代碼:

<!-- 配置使用查詢緩存 -->
<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>


3. 由於查詢使用了 hibernateTemplate,所以還要在 hibernateTemplate 中做相應配置,找到 hibernateTemplate 的配置項,添加如下代碼:

<!-- 使用查詢緩存 -->
<property name="cacheQueries">
	<value>true</value>
</property>



4. 在要緩存的實體類中加入如下註解:

@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)

注:

  usage 可以有以下幾個取值:

  • CacheConcurrencyStrategy.NONE:不使用緩存,默認;
  • CacheConcurrencyStrategy.READ_ONLY:只讀模式,若對緩存的數據進行修改操作會拋出異常;
  • CacheConcurrencyStrategy.NONSTRICT_READ_WRITE:不嚴格的讀寫模式,不會對緩存的數據加鎖;
  • CacheConcurrencyStrategy.READ_WRITE:讀寫模式,在更新緩存的時候會把緩存裏面的數據換成一個鎖,其它事務如果去取相應的緩存數據,發現被鎖了,直接就去數據庫查詢;
  • CacheConcurrencyStrategy.TRANSACTIONAL:事務模式,支持事務,當事務發生回滾時,緩存中的數據也回滾,只支持 JPA 。

5. 配置 ehcache.xml 文件:

<ehcache>
   	<!-- 指定一個文件目錄,當EHCache把數據寫到硬盤上時,將把數據寫到這個目錄下 -->
    <diskStore path="java.io.tmpdir"/>
	<!-- 
		name 設置緩存的名字,他的取值爲類的完整名字或者類的集合的名字;
		maxElementsInMemory 設置基於內存的緩存可存放的對象的最大數目
		eternal 如果爲true,表示對象永遠不會過期,此時會忽略timeToIdleSeconds和timeToLiveSeconds,默認爲false;
		timeToIdleSeconds 設定允許對象處於空閒狀態的最長時間,以秒爲單位;
		timeToLiveSeconds 設定對象允許存在於緩存中的最長時間,以秒爲單位;
		overflowToDisk 如果爲true,表示當基於內存的緩存中的對象數目達到maxElementsInMemory界限,會把溢出的對象寫到基於硬盤的緩存中;
	 -->
    <!-- 設置緩存的默認數據過期策略 -->
	<defaultCache
		maxElementsInMemory="1000"
		eternal="false"
		timeToIdleSeconds="1200"
		timeToLiveSeconds="1200"
		overflowToDisk="false"
	/>
	<!-- 設定具體的第二級緩存的數據過期策略 -->
	<cache name="com.shawearn.model.User"
		maxElementsInMemory="1000"
		eternal="false"
		timeToIdleSeconds="3000"
		timeToLiveSeconds="3000"
		overflowToDisk="false" />
</ehcache>



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章