天天看點

ehcache二級緩存配置(SSH緩存的配置) (轉)

1、首先設定EhCache,導入ehcache.jar,建立配置檔案ehcache.xml,預設的位置在class-path,可以放到你的src目錄下:

<?xml version="1.0" encoding="UTF-8"?>

<ehcache>

 <diskStore path="java.io.tmpdir"/>

  <defaultCache

   maxElementsInMemory="10000" <!-- 緩存最大數目 -->

   eternal="false" <!-- 緩存是否持久 -->

   overflowToDisk="true" <!-- 是否儲存到磁盤,當系統當機時-->

   timeToIdleSeconds="300" <!-- 當緩存閑置n秒後銷毀 -->

   timeToLiveSeconds="180" <!-- 當緩存存活n秒後銷毀-->

   diskPersistent="false"

   diskExpiryThreadIntervalSeconds= "120"/>

</ehcache>

2、在Hibernate配置檔案中設定:

<!--打開二級緩存-->

<prop key="hibernate.cache.use_second_level_cache">true</prop>

<!-- 設定Hibernate的緩存接口類,這個類在Hibernate包中 -->

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

<!-- 是否使用查詢緩存 -->

<property name="hibernate.cache.use_query_cache">true</property>

如果使用spring調用Hibernate的sessionFactory的話,這樣設定:

<!--HibernateSession工廠管理 -->

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

   <property name="dataSource">

    <ref bean="datasource" />

   </property>

   <property name="hibernateProperties">

   <props>

    <prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>

    <prop key="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</prop>

    <prop key="hibernate.show_sql">true</prop>

    <prop key="hibernate.cache.use_query_cache">true</prop>

    <prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>

   </props>

 </property>

 <property name="mappingDirectoryLocations">

  <list>

   <value>/WEB-INF/classes/cn/rmic/manager/hibernate/</value>

  </list>

 </property>

</bean>

說明一下:如果不設定“查詢緩存”,那麼hibernate隻會緩存使用load()方法獲得的單個持久化對象,如果想緩存使用findall()、list()、Iterator()、createCriteria()、createQuery()等方法獲得的資料結果集的話,就需要設定hibernate.cache.use_query_cache true 才行

3、在Hbm檔案中添加<cache usage="read-only"/> 

4、如果需要“查詢緩存”,還需要在使用Query或Criteria()時設定其setCacheable(true);屬性

比如:

public List selectHql(String hql) {

getHibernateTemplate().setCacheQueries(true);

return getHibernateTemplate().find(hql);

}

轉自: http://blog.sina.com.cn/s/blog_4e345ce70100qy1d.html

繼續閱讀