Spring3.1緩存詳解

jopen 10年前發布 | 20K 次閱讀 Spring JEE框架

下面簡單介紹一下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

 

例如:

//將緩存保存進andCache,并使用參數中的userId加上一個字符串(這里使用方法名稱)作為緩存的key
@Cacheable(value="andCache",key="#userId + 'findById'")
public SystemUser findById(String userId) {
SystemUser user = (SystemUser) dao.findById(SystemUser.class, userId);
return user ;
}
//將緩存保存進andCache,并當參數userId的長度小于32時才保存進緩存,默認使用參數值及類型作為緩存的key
@Cacheable(value="andCache",condition="#userId.length < 32")
public boolean isReserved(String userId) {
System.out.println("hello andCache"+userId);
return false;
}

@CacheEvict 支持如下幾個參數:

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

key:緩存的key,默認為空,同上

condition:觸發條件,只有滿足條件的情況才會清除緩存,默認為空,支持SpEL

allEntries:true表示清除value中的全部緩存,默認為false



例如:

//清除掉指定key的緩存
@CacheEvict(value="andCache",key="#user.userId + 'findById'")
public void modifyUserRole(SystemUser user) {
System.out.println("hello andCache delete"+user.getUserId());
}

&nbsp;//清除掉全部緩存
@CacheEvict(value="andCache",allEntries=true)
public final void setReservedUsers(String[] reservedUsers) {
System.out.println("hello andCache deleteall");
}

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

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

 

了解了cache的注解之后,接下來說說如何使注解生效,其實就是需要在spring的配置文件中增加一些配置。

 

1.spring-cache

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

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

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">

 

之后添加如下聲明:

Xml代碼 
         <!-- 啟用緩存注解功能,這個是必須的,否則注解不會生效,另外,該注解一定要聲明在spring主配置文件中才會生效 -->
        <cache:annotation-driven cache-manager="cacheManager"/>
        <!-- spring自己的換管理器,這里定義了兩個緩存位置名稱 ,既注解中的value -->
        <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
            <property name="caches">
                <set>
                    <bean
                        class="org.springframework.cache.concurrent.ConcurrentCacheFactoryBean"
                        p:name="default" />
                    <bean
                        class="org.springframework.cache.concurrent.ConcurrentCacheFactoryBean"
                        p:name="andCache" />
                </set>
            </property>
        </bean>

2.spring-ehcache

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

     <!-- 啟用緩存注解功能,這個是必須的,否則注解不會生效,另外,該注解一定要聲明在spring主配置文件中才會生效 -->
    <cache:annotation-driven cache-manager="cacheManager"/>
    <!-- cacheManager工廠類,指定ehcache.xml的位置 -->
    <bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
        p:configLocation="classpath:/config/ehcache.xml" />
    <!-- 聲明cacheManager -->
    <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"
        p:cacheManager-ref="cacheManagerFactory" />
    <!-- 啟用緩存注解功能,這個是必須的,否則注解不會生效,另外,該注解一定要聲明在spring主配置文件中才會生效 -->
    <cache:annotation-driven cache-manager="cacheManager"/> 
    <!-- cacheManager工廠類,指定ehcache.xml的位置 --> 
    <bean id="cacheManagerFactory" p:configLocation="classpath:/config/ehcache.xml" /> 
    <!-- 聲明cacheManager -->
     <bean id="cacheManager" p:cacheManager-ref="cacheManagerFactory" />

     ehcache.xml

     
        <?xml version="1.0" encoding="UTF-8"?>
        <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"
            monitoring="autodetect">
            <!--
            <diskStore path="java.io.tmpdir" /> -->
            <diskStore path="E:/cachetmpdir"/>
            <defaultCache maxElementsInMemory="10000" eternal="false"
                timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true"
                maxElementsOnDisk="10000000" diskPersistent="false"
                diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" />
            <cache name="andCache" maxElementsInMemory="10000"
                maxElementsOnDisk="1000" eternal="false" overflowToDisk="true"
                diskSpoolBufferSizeMB="20" timeToIdleSeconds="300" timeToLiveSeconds="600"
                memoryStoreEvictionPolicy="LFU" />
        </ehcache>

     

    ok,這樣注解緩存就生效了。

     本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
     轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
     本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!