javascript
介绍 Spring 3.1 M1 中的缓存功能
介紹 Spring 3.1 M1 中的緩存功能- 中文版 (轉)
Spring 3.1 提供了對已有的 Spring 應用增加緩存的支持,這個特性對應用本身來說是透明的,通過緩存抽象層,使得對已有代碼的影響降低到最小。
該緩存機制針對于 Java 的方法,通過給定的一些參數來檢查方法是否已經執行,Spring 將對執行結果進行緩存,而無需再次執行方法。
可通過下列配置來啟用緩存的支持(注意使用新的schema):
?
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:cache="http://www.springframework.org/schema/cache"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd"><cache:annotation-driven />... </beans>接下來可使用 @Cacheable 和 @CacheEvict 來對緩存進行操作。
?
@Cacheable("persons") public Person profile(Long personId) { ... }以上代碼聲明了一個名為 persons 的緩存區域,當調用該方法時,Spring 會檢查緩存中是否存在 personId 對應的值。
也可以指定多個緩存區域,當你在應用有需要這樣做的話:
?
@Cacheable({"persons", "profiles"}) public Person profile(Long personId) { ... }當指定多個區域時,Spring 會一個個的檢查,一旦某個區域存在指定值時則返回。
而 @CacheEvict 則用來從緩存中清除數據,例如:
?
@CacheEvict (value = "persons", allEntries=true) public List<Person> listPersons()@CacheEvict 可以指定清除緩存的條件。
還可以指定緩存的Key:
?
@Cacheable(value="persons", key="personId") public Person profile(Long personId, Long groundId) { ... }或者根據條件決定是否緩存:
?
@Cacheable(value="persons", condition="personId > 50") public Person profile(Long personId) { ... }緩存管理器的配置:
?
<!-- generic cache manager --> <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="persons"/></set></property> </bean>基于?Ehcache?緩存的配置:
?
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhcacheCacheManager" p:cache-manager="ehcache"/><!-- Ehcache library setup --> <bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:config-location="ehcache.xml"/>如果你看不懂上面的內容,那請看?洋文版?或者
官方文檔:http://static.springsource.org/spring/docs/3.1.0.M1/spring-framework-reference/html/cache.html。
轉載于:https://www.cnblogs.com/lhj588/archive/2012/01/13/2321769.html
總結
以上是生活随笔為你收集整理的介绍 Spring 3.1 M1 中的缓存功能的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [恢]hdu 2016
- 下一篇: 注解的力量 -----Spring 2.