Spring3.1 Cache註解

來源:互聯網
上載者:User

下面簡單介紹一下spring3.1.M1中的cache功能。

spring3.1.M1中負責cache的模組是org.springframework.context-3.1.0.M1.jar

 

與2.5時的modules模組類似,3.1的註解緩衝也是在方法上聲明註解,3.1同樣提供了兩個註解:

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

@CacheEvict:負責清除緩衝

 

@Cacheable支援如下幾個參數:

value:緩衝位置名稱,不可為空,如果使用EHCache,就是ehcache.xml中聲明的cache的name

key:緩衝的key,預設為空白,既表示使用方法的參數類型及參數值作為key,支援SpEL

condition:觸發條件,只有滿足條件的情況才會加入緩衝,預設為空白,既表示全部都加入緩衝,支援SpEL

 

例如:

Java代碼  
  1. //將緩衝儲存進andCache,並使用參數中的userId加上一個字串(這裡使用方法名稱)作為緩衝的key   
  2. @Cacheable(value="andCache",key="#userId + 'findById'")  
  3. public SystemUser findById(String userId) {  
  4.     SystemUser user = (SystemUser) dao.findById(SystemUser.class, userId);        
  5.     return user ;         
  6. }  
  7. //將緩衝儲存進andCache,併當參數userId的長度小於32時才儲存進緩衝,預設使用參數值及類型作為緩衝的key  
  8. @Cacheable(value="andCache",condition="#userId.length < 32")  
  9. public boolean isReserved(String userId) {  
  10.     System.out.println("hello andCache"+userId);  
  11.     return false;  
  12. }  

 

 

@CacheEvict支援如下幾個參數:

value:緩衝位置名稱,不可為空,同上

key:緩衝的key,預設為空白,同上

condition:觸發條件,只有滿足條件的情況才會清除緩衝,預設為空白,支援SpEL

allEntries:true表示清除value中的全部緩衝,預設為false

 

例如:

Java代碼  
  1. //清除掉指定key的緩衝  
  2. @CacheEvict(value="andCache",key="#user.userId + 'findById'")  
  3. public void modifyUserRole(SystemUser user) {  
  4.          System.out.println("hello andCache delete"+user.getUserId());  
  5. }  
  6.   
  7. //清除掉全部緩衝  
  8. @CacheEvict(value="andCache",allEntries=true)  
  9. public final void setReservedUsers(String[] reservedUsers) {  
  10.     System.out.println("hello andCache deleteall");  
  11. }  

 

一般來說,我們的更新操作只需要重新整理緩衝中某一個值,所以定義緩衝的key值的方式就很重要,最好是能夠唯一,因為這樣可以準確的清除掉特定的緩衝,而不會影響到其它緩衝值

比如我這裡針對使用者的操作,使用(userId+方法名稱)的方式設定key值當然,你也可以找到更適合自己的方式去設定。

 

SpEL:Spring Expression Language

關於SpEL的介紹,可以參考如下地址:

http://static.springsource.org/spring/docs/3.1.0.M1/spring-framework-reference/html/expressions.html

 

 

瞭解了cache的註解之後,接下來說說如何使註解生效,其實就是需要在spring的設定檔中增加一些配置。

 

1.spring-cache

首先我們來看一下如何使用spring3.1自己的cache,

需要在命名空間中增加cache的配置

Xml代碼  
  1. <beans xmlns="http://www.springframework.org/schema/beans"  
  2.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
  3.      xmlns:cache="http://www.springframework.org/schema/cache"  
  4.     xsi:schemaLocation="  
  5.             http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
  6.             http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd">  

 

之後添加如下聲明:

Xml代碼  
  1.       <!-- 啟用緩衝註解功能,這個是必須的,否則註解不會生效,另外,該註解一定要聲明在spring主設定檔中才會生效 -->  
  2. <cache:annotation-driven cache-manager="cacheManager"/>  
  3.   
  4.   
  5. <!-- spring自己的換管理器,這裡定義了兩個緩衝位置名稱 ,既註解中的value -->  
  6. <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">  
  7.     <property name="caches">  
  8.         <set>  
  9.             <bean  
  10.                 class="org.springframework.cache.concurrent.ConcurrentCacheFactoryBean"  
  11.                 p:name="default" />  
  12.             <bean  
  13.                 class="org.springframework.cache.concurrent.ConcurrentCacheFactoryBean"  
  14.                 p:name="andCache" />  
  15.         </set>  
  16.     </property>  
  17. </bean>   

 

2.spring-ehcache

接下來說說對ehcache的支援,其實只需要把cacheManager換成EHCache的cacheManager即可,如下:

Xml代碼  
  1.        <!-- 啟用緩衝註解功能,這個是必須的,否則註解不會生效,另外,該註解一定要聲明在spring主設定檔中才會生效 -->  
  2. <cache:annotation-driven cache-manager="cacheManager"/>  
  3.   
  4. <!-- cacheManager工廠類,指定ehcache.xml的位置 -->   
  5. <bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"   
  6.     p:configLocation="classpath:/config/ehcache.xml" />   
  7.   
  8. <!-- 聲明cacheManager -->  
  9. <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"   
  10.     p:cacheManager-ref="cacheManagerFactory" />  

 

 

 ehcache.xml

Xml代碼  
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.     xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"  
  4.     monitoring="autodetect">  
  5.     <!--  
  6.     <diskStore path="java.io.tmpdir" /> -->  
  7.     <diskStore path="E:/cachetmpdir"/>  
  8.     <defaultCache maxElementsInMemory="10000" eternal="false"  
  9.         timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true"  
  10.         maxElementsOnDisk="10000000" diskPersistent="false"  
  11.         diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" />  
  12.           
  13.     <cache name="andCache" maxElementsInMemory="10000"  
  14.         maxElementsOnDisk="1000" eternal="false" overflowToDisk="true"  
  15.         diskSpoolBufferSizeMB="20" timeToIdleSeconds="300" timeToLiveSeconds="600"  
  16.         memoryStoreEvictionPolicy="LFU" />  
  17. </ehcache>    

 

 

ok,這樣註解緩衝就生效了。

 

 附件中是我自己寫的一個小例子,工程結構如下所示,運行com.piaoyi.function.demo下的DemoTest即可

 

參考資料:

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

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.