EhCache是Hibernate的二級緩存技術之一,可以把查詢出來的數據存儲在內存或者磁盤,節省下次同樣查詢語句再次查詢數據庫,大幅減輕數據庫壓力;
EhCache的使用註意點
當用Hibernate的方式修改表數據(save,update,delete等等),這時EhCache會自動把緩存中關於此表的所有緩存全部刪除掉(這樣能達到同步)。但對於數據經常修改的表來說,可能就失去緩存的意義瞭(不能減輕數據庫壓力);
在比較少更新表數據的情況下,EhCache一般要使用在比較少執行write操作的表(包括update,insert,delete等)[Hibernate的二級緩存也都是這樣];對並發要求不是很嚴格的情況下,兩臺機子中的緩存是不能實時同步的;
首先要在hibernate.cfg.xml配置文件中添加如下配置
[html]
在Hibernate.cfg.xml中的mapping標簽上面加以下內容:
<!– Hibernate 3.3 and higher –>
<!–
<property name="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.EhCacheRegionFactory</property>
<property name="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.SingletonEhCacheRegionFactory</property>
–>
<!– hibernate3.0-3.2 cache config–>
<!–
<property name="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.EhCacheProvider</property>
–>
<property name="hibernate.cache.provider_class">net.sf.ehcache.hibernate.SingletonEhCacheProvider</property>
<!– Enable Second-Level Cache and Query Cache Settings –>
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.use_query_cache">true</property>
如果你是整合在spring配置文件中,那麼你得配置你的applicationContext.xml中相關SessionFactory的配置
[html]
<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>
然後在hibernate.cfg.xml配置文件中加入使用緩存的屬性
[html]
<!– class-cache config –>
<class-cache class="com.hoo.hibernate.entity.User" usage="read-write" />
當然你也可以在User.hbm.xml映射文件需要Cache的配置class節點下,加入類似如下格式信息:
[html]
<class name="com.hoo.hibernate.entity.User" table="USER" lazy="false">
<cache usage="transactional|read-write|nonstrict-read-write|read-only" />
註意:cache節點元素應緊跟class元素
關於選擇緩存策略依據:
ehcache不支持transactional,其他三種可以支持。
read-only:無需修改, 可以對其進行隻讀緩存,註意:在此策略下,如果直接修改數據庫,即使能夠看到前臺顯示效果,但是將對象修改至cache中會報error,cache不會發生作用。另:刪除記錄會報錯,因為不能在read-only模式的對象從cache中刪除。
read-write:需要更新數據,那麼使用讀/寫緩存比較合適,前提:數據庫不可以為serializable transaction isolationlevel(序列化事務隔離級別)
nonstrict-read-write:隻偶爾需要更新數據(也就是說,兩個事務同時更新同一記錄的情況很不常見),也不需要十分嚴格的事務隔離,那麼比較適合使用非嚴格讀/寫緩存策略。
如果你使用的註解方式,沒有User.hbm.xml,那麼你也可以用註解方式配置緩存
[java]
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class User implements Serializable {
}
在Dao層使用cache,代碼如下
[java]
Session s = HibernateSessionFactory.getSession();
Criteria c = s.createCriteria(User.class);
c.setCacheable(true);//這句必須要有
System.out.println("第一次讀取");
List<User> users = c.list();
System.out.println(users.size());
HibernateSessionFactory.closeSession();
s = HibernateSessionFactory.getSession();
c = s.createCriteria(User.class);
c.setCacheable(true);//這句必須要有
System.out.println("第二次讀取");
users = c.list();
System.out.println(users.size());
HibernateSessionFactory.closeSession();
你會發現第二次查詢沒有打印sql語句,而是直接使用緩存中的對象。
如果你的Hibernate和Spring整合在一起,那麼你可以用HibernateTemplate來設置cache
[java]
getHibernateTemplate().setCacheQueries(true);
return getHibernateTemplate().find("from User");
當你整合Spring時,如果你的HibernateTemplate模板配置在Spring的Ioc容器中,那麼你可以這樣啟用query cache
[html]
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
<property name="cacheQueries">
<value>true</value>
</property>
</bean>
此後,你在dao模塊中註入sessionFactory的地方都註入hibernateTemplate即可。
以上講到的都是Spring和Hibernate的配置,下面主要結合上面使用的ehcache,來完成ehcache.xml的配置。如果你沒有配置ehcache,默認情況下使用defaultCache的配置。
[html]
<cache name="com.hoo.hibernate.entity.User" maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="300" timeToLiveSeconds="600" overflowToDisk="true" />
<!–
hbm文件查找cache方法名的策略:如果不指定hbm文件中的region="ehcache.xml中的name的屬性值",則使用name名為com.hoo.hibernate.entity.User的cache,如果不存在與類名匹配的cache名稱,則用 defaultCache。
如果User包含set集合,則需要另行指定其cache
例如User包含citySet集合,則需要
添加如下配置到ehcache.xml中
–>
<cache name="com.hoo.hibernate.entity.citySet"
maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="300"
timeToLiveSeconds="600" overflowToDisk="true" />
如果你使用瞭Hibernate的查詢緩存,需要在ehcache.xml中加入下面的配置
[html]
<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" />
調試時候使用log4j的log4j.logger.org.hibernate.cache=debug,更方便看到ehcache的操作過程,主要用於調試過程,實際應用發佈時候,請註釋掉,以免影響性能。
使用ehcache,打印sql語句是正常的,因為query cache設置為true將會創建兩個緩存區域:一個用於保存查詢結果集(org.hibernate.cache.StandardQueryCache); 另一個則用於保存最近查詢的一系列表的時間戳(org.hibernate.cache.UpdateTimestampsCache)。請註意:在查詢 緩存中,它並不緩存結果集中所包含的實體的確切狀態;它隻緩存這些實體的標識符屬性的值、以及各值類型的結果。需要將打印sql語句與最近的cache內容相比較,將不同之處修改到cache中,所以查詢緩存通常會和二級緩存一起使用。
作者:IBM_hoojo