1. 程式人生 > >MyBatis框架——二級快取-整合ehcache 快取框架

MyBatis框架——二級快取-整合ehcache 快取框架

1.加入ehcache包
ehcache-core-2.6.5.jar和mybatis-ehcache-1.0.2.jar
一個是ehcache自己的,一個是和mybatis的整合包

2.整合ehcache
配置mapper中cache中的type為ehcache對cache介面的實現型別。
我們在mybatis-ehcache-1.0.2.jar下找到org.mybatis.caches.ehcache包下有EhcacheCache.class類,這個就是ehcache整合mybatis的Cache介面的實現
UserMapper.xml:

<mapper namespace
="com.popo.UserMapper">
<!-- 開啟本Mapper的namespace下的二級快取 type:執行cache介面實現類的型別,mybatis預設使用PerpatualCache, 要和ehcache整合,需要配置type為ehcache實現cache介面的型別--> <cache type="org.mybatis.caches.ehcache.EhcacheCache"/> ...... </mapper>

3.加入ehcache的配置檔案
在classpath下配置ehcache.xml
程式碼如下:

<?xml version="1.0" encoding="UTF-8" ?>
<ehcache
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../config/ehcache.xsd"
>
    <!-- 
        磁碟儲存:將快取中暫時不使用的物件,轉移到硬碟,類似於Windows系統的虛擬記憶體
        path:指定在硬碟上儲存物件的路徑
     -->
    <!-- <diskStore path="java.io.tmpdir" /> -->
<!-- 指定磁碟資料夾儲存快取 --> <diskStore path="D:\ehcache3\ehcache-cache"/> <!-- defaultCache:預設的快取配置資訊,如果不加特殊說明,則所有物件按照此配置項處理 maxElementsInMemory:設定了快取的上限,最多儲存多少個記錄物件 eternal:代表物件是否永不過期 timeToIdleSeconds:最大的發呆時間 timeToLiveSeconds:最大的存活時間 overflowToDisk:是否允許物件被寫入到磁碟 --> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" /> <!-- cache:為指定名稱的物件進行快取的特殊配置 name:指定物件的完整名 --> <cache name="com.zbaccp.entity.Person" maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="300" timeToLiveSeconds="600" overflowToDisk="true" /> </ehcache>

4.ehcache.xml屬性配置詳解

1、diskStore :指定資料(.data and .index)儲存位置,可指定磁碟中的資料夾位置期 The diskStore element is optional. It must be configured if you have overflowToDisk or diskPersistent enabled for any cache. If it is not configured, a warning will be issues and java.io.tmpdir will be used.

2、defaultCache : 預設的管理策略
一、以下屬性是必須的:
  1、name: Cache的名稱,必須是唯一的(ehcache會把這個cache放到HashMap裡)。
  2、maxElementsInMemory:在記憶體中快取的element的最大數目。
  3、maxElementsOnDisk:在磁碟上快取的element的最大數目,預設值為0,表示不限制。
  4、eternal:設定快取的elements是否永遠不過期。如果為true,則快取的資料始終有效,如果為false那麼還要根據timeToIdleSeconds,timeToLiveSeconds判斷。
  5、overflowToDisk: 如果記憶體中資料超過記憶體限制,是否要快取到磁碟上。
二、以下屬性是可選的:
  1、timeToIdleSeconds: 物件空閒時間,指物件在多長時間沒有被訪問就會失效。只對eternal為false的有效。預設值0,表示一直可以訪問。
  2、timeToLiveSeconds: 物件存活時間,指物件從建立到失效所需要的時間。只對eternal為false的有效。預設值0,表示一直可以訪問。
  3、diskPersistent: 是否在磁碟上持久化。指重啟jvm後,資料是否有效。預設為false。
  4、diskExpiryThreadIntervalSeconds: 物件檢測執行緒執行時間間隔。標識物件狀態的執行緒多長時間執行一次。
  5、diskSpoolBufferSizeMB: DiskStore使用的磁碟大小,預設值30MB。每個cache使用各自的DiskStore。
  6、memoryStoreEvictionPolicy: 如果記憶體中資料超過記憶體限制,向磁碟快取時的策略。預設值LRU,可選FIFO、LFU。
三、快取的3 種清空策略 :
  1、FIFO ,first in first out (先進先出).
  2、LFU , Less Frequently Used (最少使用).意思是一直以來最少被使用的。快取的元素有一個hit 屬性,hit 值最小的將會被清出快取。
  3、LRU ,Least Recently Used(最近最少使用,即未被使用時間最長). (ehcache 預設值).快取的元素有一個時間戳,當快取容量滿了,而又需要騰出地方來快取新的元素的時候,那麼現有快取元素中時間戳離當前時間最遠的元素將被清出快取。