知識積累(十六)——使用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中,所以查詢緩存通常會和二級緩存一起使用。
小結:具體性能需要到服務器上進行測試,目前可以通過log4j監控ehcache的變化過程。理解不當之處會在今後的工作中繼續完善修改!謝謝!

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