1.EhCache是什么
EhCache是Hibernate的二級(jí)緩存技術(shù)之一,可以把查詢出來(lái)的數(shù)據(jù)存儲(chǔ)在內(nèi)存或者磁盤,節(jié)省下次同樣查詢語(yǔ)句再次查詢數(shù)據(jù)庫(kù),大幅減輕數(shù)據(jù)庫(kù)壓力;
2.EhCache的使用注意點(diǎn)
當(dāng)用Hibernate的方式修改表數(shù)據(jù)(save,update,delete等等),這時(shí)EhCache會(huì)自動(dòng)把緩存中關(guān)于此表的所有緩存全部刪除掉(這樣能達(dá)到同步)。但對(duì)于數(shù)據(jù)經(jīng)常修改的表來(lái)說(shuō),可能就失去緩存的意義了(不能減輕數(shù)據(jù)庫(kù)壓力);
3.EhCache使用的場(chǎng)合
3.1比較少更新表數(shù)據(jù)
EhCache一般要使用在比較少執(zhí)行write操作的表(包括update,insert,delete等)[Hibernate的二級(jí)緩存也都是這樣];
3.2對(duì)并發(fā)要求不是很嚴(yán)格的情況
兩臺(tái)機(jī)子中的緩存是不能實(shí)時(shí)同步的;
4.在項(xiàng)目做的實(shí)現(xiàn)
4.1在工程的src目錄下添加ehcache.xml文件,內(nèi)容如下:
<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
<diskStore path="java.io.tmpdir" />
<defaultCache maxElementsInMemory="5"<!--緩存可以存儲(chǔ)的總記錄量-->
eternal="false"<!--緩存是否永遠(yuǎn)不銷毀-->
overflowToDisk="true"<!--當(dāng)緩存中的數(shù)據(jù)達(dá)到最大值時(shí),是否把緩存數(shù)據(jù)寫入磁盤-->
timeToIdleSeconds="15"<!--當(dāng)緩存閑置時(shí)間超過(guò)該值,則緩存自動(dòng)銷毀-->
timeToLiveSeconds="120"<!--緩存創(chuàng)建之后,到達(dá)該緩存自動(dòng)銷毀-->
/>
</ehcache>
4.2在Hibernate.cfg.xml中的mapping標(biāo)簽上面加以下內(nèi)容:
<property name="show_sql">true</property>
<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<property name="hibernate.cache.use_query_cache">true</property>
4.3在要緩存的bean的hbm.xml文件中的class標(biāo)簽下加入以下內(nèi)容:
<cache usage="read-only" /><!--也可讀寫-->
4.4創(chuàng)建DAO,內(nèi)容如下:
Session s = HibernateSessionFactory.getSession();
Criteria c = s.createCriteria(Xyz.class);
c.setCacheable(true);//這句必須要有
System.out.println("第一次讀取");
List l = c.list();
System.out.println(l.size());
HibernateSessionFactory.closeSession();
s = HibernateSessionFactory.getSession();
c = s.createCriteria(Xyz.class);
c.setCacheable(true);//這句必須要有
System.out.println("第二次讀取");
l = c.list();
System.out.println(l.size());
HibernateSessionFactory.closeSession();
4.5這時(shí)你會(huì)看到打印出來(lái)的信息為(表示第二次并沒有去讀庫(kù)):
第一次讀取
Hibernate: *******
13
第二次讀取
13
配置Spring+hibernate使用ehcache作為second-level cache
大量數(shù)據(jù)流動(dòng)是web應(yīng)用性能問題常見的原因,而緩存被廣泛的用于優(yōu)化數(shù)據(jù)庫(kù)應(yīng)用。cache被設(shè)計(jì)為通過(guò)保存從數(shù)據(jù)庫(kù)里load的數(shù)據(jù)來(lái)減少應(yīng)用和數(shù)據(jù) 庫(kù)之間的數(shù)據(jù)流動(dòng)。數(shù)據(jù)庫(kù)訪問只有當(dāng)檢索的數(shù)據(jù)不在cache里可用時(shí)才必要。hibernate可以用兩種不同的對(duì)象緩存:first-level cache 和 second-level cache。first-level cache和Session對(duì)象關(guān)聯(lián),而second-level cache是和Session Factory對(duì)象關(guān)聯(lián)。
缺省地,hibernate已經(jīng)使用基于每個(gè)事務(wù)的first-level cache。 Hibernate用first-level cache主要是減少在一個(gè)事務(wù)內(nèi)的sql查詢數(shù)量。例如,如果一個(gè)對(duì)象在同一個(gè)事務(wù)內(nèi)被修改多次,hibernate將只生成一個(gè)包括所有修改的 UPDATE SQL語(yǔ)句。為了減少數(shù)據(jù)流動(dòng),second-level cache在Session Factory級(jí)的不同事務(wù)之間保持load的對(duì)象,這些對(duì)象對(duì)整個(gè)應(yīng)用可用,不只是對(duì)當(dāng)前用戶正在運(yùn)行的查詢。這樣,每次查詢將返回已經(jīng)load在緩存 里的對(duì)象,避免一個(gè)或更多潛在的數(shù)據(jù)庫(kù)事務(wù)。
下載ehcache,hibernate3.2必須要ehcache1.2以上才能支持。可以修改log4j配置文件log4j.logger.net.sf.hibernate.cache=debug查看日志
1.在類路徑上ehcache.xml:
<ehcache>
<!-- Sets the path to the directory where cache .data files are created.
If the path is a Java System Property it is replaced by
its value in the running VM.The following properties are translated:
user.home - User's home directory
user.dir - User's current working directory
java.io.tmpdir - Default temp file path -->
<diskStore path="java.io.tmpdir"/>
<!--Default Cache configuration. These will applied to caches programmatically created through
the CacheManager.The following attributes are required:
maxElementsInMemory - Sets the maximum number of objects that will be created in memory
eternal - Sets whether elements are eternal. If eternal, timeouts are ignored and the
element is never expired.
overflowToDisk - Sets whether elements can overflow to disk when the in-memory cache
has reached the maxInMemory limit.The following attributes are optional:
timeToIdleSeconds - Sets the time to idle for an element before it expires.
i.e. The maximum amount of time between accesses before an element expires
Is only used if the element is not eternal.
Optional attribute. A value of 0 means that an Element can idle for infinity.
The default value is 0.
timeToLiveSeconds - Sets the time to live for an element before it expires.
i.e. The maximum time between creation time and when an element expires.
Is only used if the element is not eternal.
Optional attribute. A value of 0 means that and Element can live for infinity.
The default value is 0.
diskPersistent - Whether the disk store persists between restarts of the Virtual Machine.
The default value is false.
diskExpiryThreadIntervalSeconds- The number of seconds between runs of the disk expiry thread. The default value
is 120 seconds.
--><defaultCache
maxElementsInMemory="10000"
eternal="false"
overflowToDisk="true"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"/>
<!-- See http://ehcache.sourceforge.net/documentation/#mozTocId258426 for how to configure caching for your objects -->
</ehcache>
2.applicationContext-hibernate.xml里Hibernate SessionFactory配置:
<!-- Hibernate SessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation"><value>classpath:hibernate.cfg.xml</value></property>
<!-- The property below is commented out b/c it doesn't work when run via
Ant in Eclipse. It works fine for individual JUnit tests and in IDEA ??
<property name="mappingJarLocations">
<list><value>file:dist/appfuse-dao.jar</value></list>
</property>
-->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">@HIBERNATE-DIALECT@</prop>
<!--<prop key="hibernate.show_sql">true</prop>-->
<prop key="hibernate.max_fetch_depth">3</prop>
<prop key="hibernate.hibernate.use_outer_join">true</prop>
<prop key="hibernate.jdbc.batch_size">10</prop>
<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>
<!--
<prop key="hibernate.use_sql_comments">false</prop>
-->
<!-- Create/update the database tables automatically when the JVM starts up
<prop key="hibernate.hbm2ddl.auto">update</prop> -->
<!-- Turn batching off for better error messages under PostgreSQL
<prop key="hibernate.jdbc.batch_size">0</prop> -->
</props>
</property>
<property name="entityInterceptor">
<ref local="auditLogInterceptor"/>
</property>
</bean>
說(shuō)明:如果不設(shè)置“查詢緩存”,那么hibernate只會(huì)緩存使用load()方法獲得的單個(gè)持久化對(duì)象,如果想緩存使用findall()、 list()、Iterator()、createCriteria()、createQuery()等方法獲得的數(shù)據(jù)結(jié)果集的話,就需要設(shè)置 hibernate.cache.use_query_cache true 才行
3.model類里采用Xdoclet生成*.hbm.xml里的cache xml標(biāo)簽,即<cache usage="read-only"/>
/**
* @hibernate.class table="WF_WORKITEM_HIS"
* @hibernate.cache usage="read-write"
*
*/
4.對(duì)于"query cache",需要在程序里編碼:
getHibernateTemplate().setCacheQueries(true);
return getHibernateTemplate().find(hql);
<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中。在各個(gè)DAO的bean中,更改如下
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
改為
<property name="hibernateTemplate">
<ref bean="hibernateTemplate" />
</property>
2、ehcache.xml文件放在classes根目錄即可
3、pojo與ehcache.xml的配置關(guān)系
以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標(biāo)簽下面,其他位置無(wú)效。
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" />
另,針對(duì)查詢緩存的配置如下:
<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、選擇緩存策略依據(jù):
<cache usage="transactional|read-write|nonstrict-read-write|read-only" />
ehcache不支持transactional,其他三種可以支持。
read- only:無(wú)需修改, 那么就可以對(duì)其進(jìn)行只讀 緩存,注意,在此策略下,如果直接修改數(shù)據(jù)庫(kù),即使能夠看到前臺(tái)顯示效果,但是將對(duì)象修改至cache中會(huì)報(bào)error,cache不會(huì)發(fā)生作用。另:刪 除記錄會(huì)報(bào)錯(cuò),因?yàn)椴荒茉趓ead-only模式的對(duì)象從cache中刪除。
read-write:需要更新數(shù)據(jù),那么使用讀/寫緩存 比較合適,前提:數(shù)據(jù)庫(kù)不可以為serializable transaction isolation level(序列化事務(wù)隔離級(jí)別)
nonstrict-read-write:只偶爾需要更新數(shù)據(jù)(也就是說(shuō),兩個(gè)事務(wù)同時(shí)更新同一記錄的情況很不常見),也不需要十分嚴(yán)格的事務(wù)隔離,那么比較適合使用非嚴(yán)格讀/寫緩存策略。
5、調(diào)試時(shí)候使用log4j的log4j.logger.org.hibernate.cache=debug,更方便看到ehcache的操作過(guò)程,主要用于調(diào)試過(guò)程,實(shí)際應(yīng)用發(fā)布時(shí)候,請(qǐng)注釋掉,以免影響性能。
6、 使用ehcache,打印sql語(yǔ)句是正常的,因?yàn)閝uery cache設(shè)置為true將會(huì)創(chuàng)建兩個(gè)緩存區(qū)域:一個(gè)用于保存查詢結(jié)果集 (org.hibernate.cache.StandardQueryCache); 另一個(gè)則用于保存最近查詢的一系列表的時(shí)間戳(org.hibernate.cache.UpdateTimestampsCache)。請(qǐng)注意:在查詢 緩存中,它并不緩存結(jié)果集中所包含的實(shí)體的確切狀態(tài);它只緩存這些實(shí)體的標(biāo)識(shí)符屬性的值、以及各值類型的結(jié)果。需要將打印sql語(yǔ)句與最近的cache內(nèi) 容相比較,將不同之處修改到cache中,所以查詢緩存通常會(huì)和二級(jí)緩存一起使用。