Spring3.1 已加緩存的實現,今天主要介紹一下Spring Cache的基本使用,要想使你的程序具體緩存的功能,首先須要在配置文件中增長如下配置:css
一、若是使用Annotation 方式配置緩存,須要有如下配置:html
<cache:annotation-driven />
默認的緩存管理器的名字爲cacheManager,若是須要指定緩存管理器名稱,須要指定其名稱
如:
<cache:annotation-driven cache-manager="cacheManager"/>
設置好註解配置事後,須要設置緩存管理器。spring
<!-- 緩存管理器聲明--> <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager"> <property name="caches"> <set> <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" p:name="default"/> <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" p:name="base"/> </set> </property> </bean>
當前配置的是用ConcurrentMap做爲緩存容器,固然,也能夠自定義緩存容器,具體參見srping 文檔,上述配置指定的兩個緩存管理器,分別爲:default,base。緩存
完整配置以下:spa
1: <beans xmlns="http://www.springframework.org/schema/beans"
2: xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3: xmlns:cache="http://www.springframework.org/schema/cache"
4: xmlns:p="http://www.springframework.org/schema/p"
5: xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
6: http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
7:
8:
9: <cache:annotation-driven cache-manager="cacheManager"/>
10:
11:
12: <!-- 緩存管理器聲明-->
13: <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
14: <property name="caches">
15: <set>
16: <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" p:name="default"/>
17: <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" p:name="base"/>
18: </set>
19: </property>
20: </bean>
21:
22: </beans>
二、XML配置好事後,如何在程序中使用,請看下面介紹code
若是須要緩存某個業務的字典數據,可直接在方法增長Cacheable標
xml
@Cacheable(value = "base", key = "#root.methodName") public List<String> getCredits() { logger.info("開始查詢證件類型"); List<String> credits = new ArrayList<String>(); credits.add("身份證"); credits.add("軍官證"); credits.add("學生證"); return credits; }
在該方法上增長@Cacheable註解,Spring會自動把返回的數據加到緩存中,而且把數據緩存在base容器中,同時設定的key的名稱爲: 方法名。
key的名稱定能夠採用SPEL表達式。htm
@Cacheable(value = "base", key = "#type") public List<String> findSeats(String type) { List<String> seats = new ArrayList<String>(); if ("seat".equals(type)) { logger.info("開始查詢席位類型"); int base = 97; // 構建Seat記錄 for (int i = 0; i < 26; i++) { int tmp = base + i; seats.add(String.valueOf((char) tmp)); } } else if ("ticket".equals(type)) { logger.info("開始查詢票種類型"); int base = 65; // 構建Seat記錄 for (int i = 0; i < 26; i++) { int tmp = base + i; seats.add(String.valueOf((char) tmp)); } } return seats; }
該示例演示了,緩存的數據以type爲key。rem
三、緩存數據更新文檔
示例:
/** * 當發生席位記錄變動,須要清除現有的緩存。 */ @CacheEvict(value = "base", key = "#type") public void updateSeats(String type) { logger.info("開始更新席位記錄"); }
在更新的方法中,增長@CacheEvict 註解,而且要指定須要更新的是哪一個容器和key,若是沒有指定key,那該容器的全部數據都會更新。