Spring 3.1 M1 中的缓存功能

本文转自:http://www.oschina.net/question/12_16549

上个月 Spring 发布了 3.1 的第一个里程碑版本,详情请看这里

该版本最酷的新特性就是引入全方位的缓存支持。Spring 3.1 提供了对已有的 Spring 应用增加缓存的支持,这个特性对应用本身来说是透明的,通过缓存抽象层,使得对已有代码的影响降低到最小。

该缓存机制针对于 Java 的方法,通过给定的一些参数来检查方法是否已经执行,Spring 将对执行结果进行缓存,而无需再次执行方法。

可通过下列配置来启用缓存的支持(注意使用新的schema):

 

 
  1. <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  2.   xmlns:cache="http://www.springframework.org/schema/cache" 
  3.    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  
  4.         http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd"> 
  5.    
  6.   <cache:annotation-driven /> 
  7.   ...  
  8. </beans> 

接下来可使用 @Cacheable 和 @CacheEvict 来对缓存进行操作。

 

 
  1. @Cacheable("persons")  
  2. public Person profile(Long personId) { ... } 

以上代码声明了一个名为 persons 的缓存区域,当调用该方法时,Spring 会检查缓存中是否存在 personId 对应的值。

也可以指定多个缓存区域,当你在应用有需要这样做的话:

 

 
  1. @Cacheable({"persons""profiles"})  
  2. public Person profile(Long personId) { ... } 

当指定多个区域时,Spring 会一个个的检查,一旦某个区域存在指定值时则返回。

而 @CacheEvict 则用来从缓存中清除数据,例如:

 

 
  1. @CacheEvict (value = "persons", allEntries=true)  
  2. public List<Person> listPersons() 

@CacheEvict 可以指定清除缓存的条件。

还可以指定缓存的Key:

 

 
  1. @Cacheable(value="persons", key="personId")  
  2. public Person profile(Long personId, Long groundId) { ... } 

或者根据条件决定是否缓存:

 

 
  1. @Cacheable(value="persons", condition="personId > 50")  
  2. public Person profile(Long personId) { ... } 

缓存管理器的配置:

 

 
  1. <!-- generic cache manager --> 
  2. <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager"> 
  3.   <property name="caches"> 
  4.     <set> 
  5.       <bean class="org.springframework.cache.concurrent.ConcurrentCacheFactoryBean" p:name="default"/> 
  6.       <bean class="org.springframework.cache.concurrent.ConcurrentCacheFactoryBean" p:name="persons"/> 
  7.     </set> 
  8.   </property> 
  9. </bean> 

基于 Ehcache 缓存的配置:

 

 
  1. <bean id="cacheManager" class="org.springframework.cache.ehcache.EhcacheCacheManager" p:cache-manager="ehcache"/> 
  2.    
  3. <!-- Ehcache library setup --> 
  4. <bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:config-location="ehcache.xml"/>  

如果你看不懂上面的内容,那请看 洋文版

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值