要實現基於注解的緩存實現,要求Spring的版本在3.1或以上版本。
首先需要在spring的配置文件中添加對緩存注解的實現:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:context="http://www.springframework.org/schema/context" xmlns:cache="http://www.springframework.org/schema/cache" http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd"> <context:component-scan base-package="com.xxx" /> <!-- 啟用緩存注解功能 --> <cache:annotation-driven cache-manager="ehcacheManager"/> <bean id="ehcacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> <property name="configLocation" value="classpath:ehcache.xml" /> </bean> <bean id="ehcacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"> <property name="cacheManager" ref="ehcacheManagerFactory" /> </bean> </beans>
ehcache.xml
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd"> <diskStore path="java.io.tmpdir" /> <defaultCache name="defaultCache" maxElementsInMemory="300" timeToLiveSeconds="1800" eternal="false" overflowToDisk="true" /> <cache name="springCache" maxElementsInMemory="300" timeToLiveSeconds="1800" eternal="false" overflowToDisk="true"/> </ehcache>
注解的使用:
@Service public class MyServiceImpl implements MyService { ...... @Cacheable(value="springCache",key="'userlist_' + #param['username']") public List<Map<String, Object>> queryUserList(Map<String, Object> param) throws Exception { return userDAO.queryUserList(param); } ...... }
添加了@Cacheable的注解,value屬性設為固定值springCache,該值對應ehcache.xml文件中cache的name,key屬性設為緩存的名稱,可以是一個固定值,比如’userlist’,也可以添加上請求方法的屬性值,比如’userlist_’ + #param[‘username’],用於確保輸入參數不同,輸出的值不同的情況。
除了@Cacheable注解,還有@CachePut和@CacheEvict兩個注解,區別在於:
@Cacheable:如果使用@Cacheable注解,先檢查對應的緩存是否存在,如果緩存存在,直接取緩存值返回,不再執行方法體內容;如果緩存不存在,則執行方法體內容,並且將返回的內容寫入緩存
@CachePut:使用@CachePut注解和@Cacheable注解類似,只是不管對應緩存是否存在,都執行方法體,並且將返回的內容寫入緩存
@CacheEvict:@CacheEvict注解表示對應緩存的刪除
緩存的使用總結:
在讀取數據時,使用@Cacheable注解將數據加入緩存
在數據發生改變時,使用@CachePut注解更新緩存
在數據被刪除時,使用@CacheEvict注解刪除緩存