SSM整合ehcache

SSM整合ehcache

EhCache 是一個純Java的進程內緩存框架,具有快速、精幹等特點,是Hibernate中默認的CacheProvider。mybatis需要自己整合;

下面開始整合mybatis和Ehcache

1.使用首先要把需要的jar包依賴加入pom中

 <dependency>
	<groupId>org.mybatis</groupId>
	<artifactId>mybatis-ehcache</artifactId>
	<version>1.0.0</version>
 </dependency>
 <dependency>
	<groupId>org.ehcache</groupId>
	<artifactId>ehcache</artifactId>
	<version>3.0.0.m3</version>
 </dependency>

2.在Resource中添加一個ehcache.xml的配置文件

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
	updateCheck="false">
       <diskStore path="java.io.tmpdir" />
       <defaultCache eternal="false" maxElementsInMemory="1000"
		   overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0"
		   timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU" />
       <cache name="testCache" eternal="false" maxElementsInMemory="100"
	     overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0"
	     timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU" />
</ehcache>

說明:

name:Cache的唯一標識  
maxElementsInMemory:內存中最大緩存對象數  
maxElementsOnDisk:磁盤中最大緩存對象數,若是0表示無窮大  
eternal:Element是否永久有效,一但設置了,timeout將不起作用  
overflowToDisk:配置此屬性,當內存中Element數量達到maxElementsInMemory時,Ehcache將會Element寫到磁盤中  
timeToIdleSeconds:設置Element在失效前的允許閒置時間。僅當element不是永久有效時使用,可選屬性,默認值是0,也就是可閒置時間無窮大  
timeToLiveSeconds:設置Element在失效前允許存活時間。最大時間介於創建時間和失效時間之間。僅當element不是永久有效時使用,默認是0.,也就是element存活時間無窮大   
diskPersistent:是否緩存虛擬機重啓期數據  
diskExpiryThreadIntervalSeconds:磁盤失效線程運行時間間隔,默認是120秒  
diskSpoolBufferSizeMB:這個參數設置DiskStore(磁盤緩存)的緩存區大小。默認是30MB。每個Cache都應該有自己的一個緩衝區  
memoryStoreEvictionPolicy:當達到maxElementsInMemory限制時,Ehcache將會根據指定的策略去清理內存。默認策略是LRU(最近最少使用)。你可以設置爲FIFO(先進先出)或是LFU(較少使用)   

3.在spring-mybatis.xml中加入chache配置

<!-- 使用ehcache緩存 -->
    <bean id="ehCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
        <property name="configLocation" value="classpath:ehcache.xml" />
    </bean>

4.在mapper.xml中配置cache

<cache type="org.mybatis.caches.ehcache.LoggingEhcache" >  
	<property name="timeToIdleSeconds" value="3600"/>
	<property name="timeToLiveSeconds" value="3600"/>
	<property name="maxEntriesLocalHeap" value="1000"/>  
	<property name="maxEntriesLocalDisk" value="10000000"/>  
	<property name="memoryStoreEvictionPolicy" value="LRU"/>  
</cache>

測試的話可以自己比較下使用ehcache和不適用ehcache查詢時間也可以吧sql語句打印出來看看;


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