Spring ehcache 緩存使用

@Cacheable:負責將方法的返回值加入到緩存中

@Cacheable(value=」accountCache」), 這個註釋的意思是,當調用這個方法的時候,會從一個名叫 accountCache 的緩存中查詢,若是沒有,則執行實際的方法(即查詢數據庫),並將執行的結果存入緩存中,不然返回緩存中的對象。這裏的緩存中的 key 就是參數 userName,value 就是 Account 對象。「accountCache」緩存是在 spring*.xml 中定義的名稱。html

value:緩存位置名稱,不能爲空,若是使用EHCache,就是ehcache.xml中聲明的cache的namejava

key:緩存的key,默認爲空,既表示使用方法的參數類型及參數值做爲key,支持SpELspring

condition:觸發條件,只有知足條件的狀況纔會加入緩存,默認爲空,既表示所有都加入緩存,支持SpEL數據庫

@Cacheable(value="accountCache",key="#userId")// 使用了一個緩存名叫 accountCache 
public Account getAccountByName(String userId) {
     // 方法內部實現不考慮緩存邏輯,直接實現業務
     return getFromDB(userId); 
}
@Cacheable(value="accountCache",condition="#userName.length() <=4")// 緩存名叫 accountCache 
public Account getAccountByName(String userName) { 
 // 方法內部實現不考慮緩存邏輯,直接實現業務
 return getFromDB(userName); 
}

 

@CacheEvict:負責清除緩存

@CacheEvict 註釋來標記要清空緩存的方法,當這個方法被調用後,即會清空緩存。注意其中一個 @CacheEvict(value=」accountCache」,key=」#account.getName()」),其中的 Key 是用來指定緩存的 key 的,這裏由於咱們保存的時候用的是 account 對象的 name 字段,因此這裏還須要從參數 account 對象中獲取 name 的值來做爲 key,前面的 # 號表明這是一個 SpEL 表達式,此表達式能夠遍歷方法的參數對象,具體語法能夠參考 Spring 的相關文檔手冊。express

value:緩存位置名稱,不能爲空,同上緩存

key:緩存的key,默認爲空,同上網絡

condition:觸發條件,只有知足條件的狀況纔會清除緩存,默認爲空,支持SpEL   關於SpEL文檔請參考:http://docs.spring.io/spring/docs/3.1.0.M1/spring-framework-reference/html/expressions.htmlspa

allEntries:true表示清除value中的所有緩存,默認爲false線程

@CacheEvict(value="accountCache",key="#account.getName()")// 清空accountCache 緩存  
public void updateAccount(Account account) {
     updateDB(account); 
} 
  
@CacheEvict(value="accountCache",allEntries=true)// 清空accountCache 緩存
public void reload() {
     reloadAll()
}

 

@CachePut:緩存與數據庫的同步更新

@CachePut 註釋,這個註釋能夠確保方法被執行,同時方法的返回值也被記錄到緩存中,實現緩存與數據庫的同步更新。code

value 緩存的名稱,在 spring 配置文件中定義,必須指定至少一個 例如:
@Cacheable(value=」mycache」) 或者 
@Cacheable(value={」cache1」,」cache2」}
key 緩存的 key,能夠爲空,若是指定要按照 SpEL 表達式編寫,若是不指定,則缺省按照方法的全部參數進行組合 例如:
@Cacheable(value=」testcache」,key=」#userName」)
condition 緩存的條件,能夠爲空,使用 SpEL 編寫,返回 true 或者 false,只有爲 true 才進行緩存 例如:
@Cacheable(value=」testcache」,condition=」#userName.len

通常適用於更新數據,這樣一來數據也被更新了,緩存中數據也被更新了

@CachePut(value="accountCache",key="#account.getName()")// 更新accountCache 緩存
public Account updateAccount(Account account) { 
   return updateDB(account); 
}

JAVA使用緩存基本用法

CacheManager cacheManager = CacheManager.create();
// 或者
cacheManager = CacheManager.getInstance();
// 或者
cacheManager = CacheManager.create("/config/ehcache.xml");
// 或者
cacheManager = CacheManager.create("http://localhost:8080/test/ehcache.xml");
cacheManager = CacheManager.newInstance("/config/ehcache.xml");
// .......
 
// 獲取ehcache配置文件中的一個cache
Cache sample = cacheManager.getCache("sample");
// 獲取頁面緩存
BlockingCache cache = new BlockingCache(cacheManager.getEhcache("SimplePageCachingFilter"));
// 添加數據到緩存中
Element element = new Element("key", "val");
sample.put(element);
// 獲取緩存中的對象,注意添加到cache中對象要序列化 實現Serializable接口
Element result = sample.get("key");
// 刪除緩存
sample.remove("key");
sample.removeAll();
 
// 獲取緩存管理器中的緩存配置名稱
for (String cacheName : cacheManager.getCacheNames()) {
    System.out.println(cacheName);
}
// 獲取全部的緩存對象
for (Object key : cache.getKeys()) {
    System.out.println(key);
}
 
// 獲得緩存中的對象數
cache.getSize();
// 獲得緩存對象佔用內存的大小
cache.getMemoryStoreSize();
// 獲得緩存讀取的命中次數
cache.getStatistics().getCacheHits();
// 獲得緩存讀取的錯失次數
cache.getStatistics().getCacheMisses();

Spring EHCACHE配置

spring-ehcache.xml配置

<beans xmlns="http://www.springframework.org/schema/beans"  
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
      xmlns:cache="http://www.springframework.org/schema/cache"  
     xsi:schemaLocation="   
             http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
            http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd">   
            
   <!-- cacheManager工廠類,指定ehcache.xml的位置 -->
   <bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
       <property name="configLocation">  
            <value>classpath:ehcache.xml</value>  
        </property>
    </bean>
   
   <!-- 聲明cacheManager -->
   <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
        <property name="cacheManager">  
           <ref local="cacheManagerFactory" />  
        </property>
   </bean>
   
   <!-- 啓用緩存註解功能,這個是必須的,不然註解不會生效-->
   <cache:annotation-driven cache-manager="cacheManager"/>
</beans>

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="true" monitoring="autodetect">

    <diskStore path="java.io.tmpdir"/>
    <!--  <diskStore path="E:/cachetmpdir" /> -->
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="600"
            timeToLiveSeconds="1200"
            overflowToDisk="false"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="1800"
            memoryStoreEvictionPolicy="LRU"
            />
    <cache name="productCache"
           maxElementsInMemory="10000"
           eternal="false"
           overflowToDisk="false"
           timeToIdleSeconds="300"
           timeToLiveSeconds="600"
           memoryStoreEvictionPolicy="LFU">
    </cache>
</ehcache>

Ehcache配置文件的詳細說明

maxElementsInMemory :cache 中最多能夠存放的元素的數量。若是放入cache中的元素超過這個數值,有兩種狀況:一、若overflowToDisk的屬性值爲true,會將cache中多出的元素放入磁盤文件中。二、若overflowToDisk的屬性值爲false,會根據memoryStoreEvictionPolicy的策略替換cache中原有的元素。

eternal :意思是是否永駐內存。若是值是true,cache中的元素將一直保存在內存中,不會由於時間超時而丟失,因此在這個值爲true的時候,timeToIdleSecondstimeToLiveSeconds兩個屬性的值就不起做用了。

timeToIdleSeconds :就是訪問這個cache中元素的最大間隔時間。若是超過這個時間沒有訪問這個cache中的某個元素,那麼這個元素將被從cache中清除。

timeToLiveSeconds : 這是cache中元素的生存時間。意思是從cache中的某個元素從建立到消亡的時間,從建立開始計時,當超過這個時間,這個元素將被從cache中清除。

overflowToDisk :溢出是否寫入磁盤。系統會根據標籤<diskStore path="java.io.tmpdir"/> 中path的值查找對應的屬性值,若是系統的java.io.tmpdir的值是 D:/temp,寫入磁盤的文件就會放在這個文件夾下。文件的名稱是cache的名稱,後綴名的data。如:CACHE_FUNC.data。這個屬性 在解釋maxElementsInMemory的時候也已經說過了。

diskExpiryThreadIntervalSeconds  :磁盤緩存的清理線程運行間隔

memoryStoreEvictionPolicy :內存存儲與釋放策略。有三個值:

LRU -least recently used

LFU -least frequently used

FIFO-first in first out, the oldest element by creation time

diskPersistent : 是否持久化磁盤緩存。當這個屬性的值爲true時,系統在初始化的時候會在磁盤中查找文件名爲cache名稱,後綴名爲index的的文件,如 CACHE_FUNC.index 。這個文件中存放了已經持久化在磁盤中的cache的index,找到後把cache加載到內存。要想把cache真正持久化到磁盤,寫程序時必須注意, 在是用net.sf.ehcache.Cachevoid put (Element element)方法後要使用void flush()方法。

以上時間值都是以秒做爲單位的。  

<diskStore>表示當內存緩存中對象數量超過類設置內存緩存數量時,將緩存對象寫到硬盤,path=」java.io.tmpdir」表示把數據寫到這個目錄下。Java.io.tmpdir目錄在運行時會根據相對路徑生成。
<defaultCache>表示設定緩存的默認數據過時策略。
<cache>表示設定用具體的命名緩存的數據過時策略。

參考資料:

http://blog.springsource.com/2011/02/23/spring-3-1-m1-caching/

http://hi.baidu.com/coolcooldool/blog/item/3b541533c72b40e21a4cffda.html

部份內容來源於網絡。

相關文章
相關標籤/搜索