1.在applicationContex.xml檔案裡面添加二級緩衝配置:
<!-- 配置hibernate的sessionFactory --><bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"><property name="dataSource"><ref bean="dataSource" /></property> <property name="mappingResources"> <list> <value>com/persia/model/Person.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <value> hibernate.dialect=org.hibernate.dialect.MySQL5Dialect hibernate.hbm2ddl.auto=update hibernate.show_sql=false hibernate.format_sql=false hibernate.cache.use_second_level_cache=true //使用二級緩衝 hibernate.cache.use_query_cache=false //不使用查詢快取,因為命中率不高 hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider //使用Ehcache </value> </property></bean>
2.添加ehcache.xml的緩衝設定檔:
<?xml version="1.0" encoding="UTF-8"?><!-- defaultCache節點為預設的緩衝策略 maxElementsInMemory 記憶體中最大允許存在的對象數量 eternal 設定緩衝中的對象是否永遠不到期 overflowToDisk 把溢出的對象存放到硬碟上 timeToIdleSeconds 指定緩衝對象空閑多長時間就到期,到期的對象會被清除掉 timeToLiveSeconds 指定緩衝對象總的存活時間 diskPersistent 當jvm結束是是否持久化對象 diskExpiryThreadIntervalSeconds 指定專門用於清除到期對象的監聽線程的輪詢時間 --><ehcache> <diskStore path="D:\cache"/> <defaultCache maxElementsInMemory="1000" eternal="false" overflowToDisk="true" timeToIdleSeconds="120" timeToLiveSeconds="180" diskPersistent="false" diskExpiryThreadIntervalSeconds="60"/> <cache name="com.persia.model.Person" maxElementsInMemory="100" eternal="false" overflowToDisk="true" timeToIdleSeconds="300" timeToLiveSeconds="600" diskPersistent="false"/></ehcache>
3.在實體bean的對應檔添加緩衝設定:
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping package="com.persia.model"> <class name="Person" table="person"> <cache usage="read-write" region="com.persia.model.Person"/> <id name="id"> <generator class="native"/> </id> <property name="name" length="30" not-null="true"/> </class></hibernate-mapping>
4.測試是否使用緩衝
第一次擷取從資料庫擷取,然後緩衝,關閉資料庫,進行第二次擷取,看是否能擷取得到。
@Testpublic void testGetPerson() {System.out.println(ps.getPerson(7).getName());try {System.out.println("請在15秒之內關閉資料庫");Thread.sleep(15*1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println("從緩衝擷取:"+ps.getPerson(7).getName());}結果:
傳智播客4
請在15秒之內關閉資料庫
從緩衝擷取:傳智播客4
查看磁碟的快取檔案: