`
473687880
  • 浏览: 535674 次
文章分类
社区版块
存档分类
最新评论

Spring3.1.M1 cache注解

 
阅读更多

需要感慨一下,spring3.0时丢弃了2.5时的spring-modules-cache.jar,致使无法使用spring来方便的管理cache注解,好在3.1.M1中增加了对cache注解的支持,可喜可贺啊!

希望了解spring2.5的cache注解,可以参考如下内容:


Spring基于注解的缓存配置--EHCache AND OSCache
Spring基于注解的缓存配置--web应用实例

2.5时,spring没有自己的解决方案,都是采用对许多第三方cache框架的支持,比如EHCache和OSCache等等,不过到了3.1,spring就只提供EHCache的支持了,不过spring3.1还给出了自己的解决方案。

下面简单介绍一下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

例如:


Java代码 复制代码收藏代码Spring3.1.M1 cache注解 - greencoat_man - greencoat_man的博客
//将缓存保存进andCache,并使用参数中的userId加上一个字符串(这里使用方法名称)作为缓存的key
@Cacheable(value="andCache",key="#userId+'findById'")
publicSystemUserfindById(StringuserId){
SystemUseruser=(SystemUser)dao.findById(SystemUser.class,userId);
returnuser;
}
//将缓存保存进andCache,并当参数userId的长度小于32时才保存进缓存,默认使用参数值及类型作为缓存的key
@Cacheable(value="andCache",condition="#userId.length<32")
publicbooleanisReserved(StringuserId){
System.out.println("helloandCache"+userId);
returnfalse;
}
       //将缓存保存进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

例如:


Java代码 复制代码收藏代码Spring3.1.M1 cache注解 - greencoat_man - greencoat_man的博客
//清除掉指定key的缓存
@CacheEvict(value="andCache",key="#user.userId+'findById'")
publicvoidmodifyUserRole(SystemUseruser){
System.out.println("helloandCachedelete"+user.getUserId());
}

//清除掉全部缓存
@CacheEvict(value="andCache",allEntries=true)
publicfinalvoidsetReservedUsers(String[]reservedUsers){
System.out.println("helloandCachedeleteall");
}
       //清除掉指定key的缓存          @CacheEvict(value="andCache",key="#user.userId + 'findById'")   public void modifyUserRole(SystemUser user) {    System.out.println("hello andCache delete"+user.getUserId());   }           //清除掉全部缓存   @CacheEvict(value="andCache",allEntries=true)   public final void setReservedUsers(String[] reservedUsers) {    System.out.println("hello andCache deleteall");   }

一般来说,我们的更新操作只需要刷新缓存中某一个值,所以定义缓存的key值的方式就很重要,最好是能够唯一,因为这样可以准确的清除掉特定的缓存,而不会影响到其它缓存值 ,

比如我这里针对用户的操作,使用(userId+方法名称)的方式设定key值 ,当然,你也可以找到更适合自己的方式去设定。

SpEL:Spring Expression Language

关于SpEL的介绍,可以参考如下地址:

http://static.springsource.org/spring/docs/3.1.0.M1/spring-framework-reference/html/expressions.html

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

1.spring-cache

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

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


Xml代码 复制代码收藏代码Spring3.1.M1 cache注解 - greencoat_man - greencoat_man的博客
<beansxmlns="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/beanshttp://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/cachehttp://www.springframework.org/schema/cache/spring-cache-3.1.xsd">
<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代码 复制代码收藏代码Spring3.1.M1 cache注解 - greencoat_man - greencoat_man的博客
<!--启用缓存注解功能,这个是必须的,否则注解不会生效,另外,该注解一定要声明在spring主配置文件中才会生效-->
<cache:annotation-drivencache-manager="cacheManager"/>


<!--spring自己的换管理器,这里定义了两个缓存位置名称,既注解中的value-->
<beanid="cacheManager"class="org.springframework.cache.support.SimpleCacheManager">
<propertyname="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>
       <!-- 启用缓存注解功能,这个是必须的,否则注解不会生效,另外,该注解一定要声明在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即可,如下:


Java代码 复制代码收藏代码Spring3.1.M1 cache注解 - greencoat_man - greencoat_man的博客
<!--启用缓存注解功能,这个是必须的,否则注解不会生效,另外,该注解一定要声明在spring主配置文件中才会生效-->
<cache:annotation-drivencache-manager="cacheManager"/>

<!--cacheManager工厂类,指定ehcache.xml的位置-->
<beanid="cacheManagerFactory"class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
p:configLocation="classpath:/config/ehcache.xml"/>

<!--声明cacheManager-->
<beanid="cacheManager"class="org.springframework.cache.ehcache.EhCacheCacheManager"
p:cacheManager-ref="cacheManagerFactory"/>
        <!-- 启用缓存注解功能,这个是必须的,否则注解不会生效,另外,该注解一定要声明在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" /> 

ehcache.xml


Xml代码 复制代码收藏代码Spring3.1.M1 cache注解 - greencoat_man - greencoat_man的博客
<?xmlversion="1.0"encoding="UTF-8"?>
<ehcachexmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd"updateCheck="true"
monitoring="autodetect">
<!--
<diskStorepath="java.io.tmpdir"/>-->
<diskStorepath="E:/cachetmpdir"/>
<defaultCachemaxElementsInMemory="10000"eternal="false"
timeToIdleSeconds="120"timeToLiveSeconds="120"overflowToDisk="true"
maxElementsOnDisk="10000000"diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"memoryStoreEvictionPolicy="LRU"/>

<cachename="andCache"maxElementsInMemory="10000"
maxElementsOnDisk="1000"eternal="false"overflowToDisk="true"
diskSpoolBufferSizeMB="20"timeToIdleSeconds="300"timeToLiveSeconds="600"
memoryStoreEvictionPolicy="LFU"/>
</ehcache>
<?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,这样注解缓存就生效了。

附件中是我自己写的一个小例子,工程结构如下所示,运行com.piaoyi.function.demo下的DemoTest即可.

参考资料:

http://blog.springsource.com/2011/02/23/spring-3-1-m1-caching/

http://hi.baidu.com/coolcooldool/blog/item/3b541533c72b40e21a4cffda.html


分享到:
评论

相关推荐

    spring3.1 官方全部jar包

    spring3.1官方所有的jar包 org.springframework.aop-3.1.RELEASE.jar org.springframework.asm-3.1.RELEASE.jar org.springframework.aspects-3.1.RELEASE.jar org.springframework.beans-3.1.RELEASE.jar org....

    Spring 3.1.x + Hibernate 4.2.x+JBPM 5.2 + Ecache例子源码

    标题中的"Spring 3.1.x + Hibernate 4.2.x + JBPM 5.2 + Ecache例子源码"代表了一个集成开发环境,其中包含了四个关键的技术组件: 1. **Spring 3.1.x**:这是一个开源的应用框架,主要用于简化Java企业级应用的...

    spring3.1.o.m2 dist

    标题中的"spring3.1.o.m2 dist"指的是Spring框架的3.1版本的一个特定发行版,其中"dist"通常代表“distribution”,意味着这是一个包含了所有发布文件的集合,供用户下载和使用。在这个上下文中,"o"可能是遗漏或者...

    spring3.x注解

    Spring 3.x 注解应用详解 Spring 3.x 框架引入了依赖注入的注解,改变了传统的 XML 配置方式,提供了一种更加灵活和方便的依赖配置方式。下面对 Spring 3.x 的注解应用进行详细的介绍。 一、属性装配 在 Spring ...

    spring-aop-3.1.xsd

    spring-aop-3.1.xsd用于spring aop开发代码提示。用于Java开发。

    struts2.3.x+spring3.1.x+hibernate4.1整合工程(好用)

    Spring3.1.x版本加强了对JSR-330注解的支持,提升了对Java EE 6的兼容性,同时增强了对RESTful服务的支持。 **Hibernate** 是一款优秀的ORM(Object-Relational Mapping,对象关系映射)框架,它将数据库操作转化为...

    struts2.2.3-hibernate3.3.1-spring3.1.zip jar 包

    Spring3.1 引入了新的特性,比如Groovy配置支持、@Scheduled定时任务注解、以及对JavaConfig的增强,使得无XML配置成为可能。`spring-framework-3.1.0.M1 jar 包.zip`包含了Spring框架的相关库文件,方便开发者在...

    H-ui.admin_v3.1.3.1.zip

    H-ui.admin_v3.1.3.1作为该框架的一个版本,为开发者提供了强大的工具集,助力构建高质量的Web应用程序。本文将详细探讨H-ui的核心特性、设计理念以及在实际开发中的应用。 1. **H-ui框架概述** H-ui是一个基于...

    Spring 3.1.x + Hibernate 4.2.x+JBPM 5.2 + Ecache例子

    标题 "Spring 3.1.x + Hibernate 4.2.x + JBPM 5.2 + Ecache 例子" 涉及的是一个集成多种技术的Java应用开发示例。这个项目可能是一个完整的业务流程管理系统,它整合了Spring、Hibernate、JBPM和Ecache等关键组件。...

    spring3.1.o.m2 src

    《Spring 3.1.0.M2 源码解析》 Spring框架是Java开发中的一个核心组件,尤其在企业级应用中广泛使用。Spring 3.1.0.M2是该框架的一个早期里程碑版本,提供了许多关键特性和改进。在这个版本中,源码解析对于理解...

    spring-context-3.1.xsd

    spring-context-3.1.xsd用于spring DI开发代码提示。用于Java开发。

    struts2.3.x+spring3.1.x+hibernate3.6 demo

    十分抱歉,上次整合的是一个半成品,spring3.1和hibernate4.1目前为止我测试了,整合过程中有很多问题!关键问题有几个,第一个HibernateDaoSupport这个没有了,在使用hibernateTemplate的时候,报错误:java.lang....

    spring-cglib-repack-3.1.jar,spring-objenesis-repack-2.1.jar

    当我们在研究或编译Spring 4.0的源码时,可能会遇到一些依赖问题,其中"spring-cglib-repack-3.1.jar"和"spring-objenesis-repack-2.1.jar"是两个关键的jar包,它们在源码编译过程中起着至关重要的作用。本文将详细...

    最新SSH开发的全部JAR集合_Struts2.3.4.1+Hibernate4.1.7+Spring3.1.20_SSH

    这个"最新SSH开发的全部JAR集合"提供了这三个框架的特定版本,分别是Struts2.3.4.1、Hibernate4.1.7和Spring3.1.20。 Struts2是Apache软件基金会下的一个开源MVC(Model-View-Controller)框架,它基于拦截器模型,...

    springsecurity3.1.pdf

    标题:springsecurity3.1.pdf 描述:springsecurity3.1.pdf 标签:spring security3.1 部分内容:SpringSecurity Reference Documentation by Ben Alex and Luke Taylor 3.1.4.RELEASE **一、Spring Security 3.1...

    spring 3.x 需要的jar包 spring-cglib-repack-3.1.jar

    `spring-cglib-repack-3.1.jar` 是Spring框架中的一个重要组件,它与动态代理有关。CGLIB(Code Generation Library)是一个强大的高性能的代码生成库,用于在运行期扩展Java类与实现Java接口。在Spring中,CGLIB...

    spring-mvc-3.1.xsd

    targetNamespace="http://www.springframework.org/schema/mvc"

    Spring Framework 3.2.0.M1 API .chm

    Spring Framework 3.2.0.M1 API .chm

    spring-cglib-repack-3.1.jar

    学spring的应该知道要熟悉spring的源码,本人是根据《spring源码深度解析》里的步骤下载了spring的源码,也使用gradle编译了一下,终于可以导入eclipse了,但是jar包依赖报错了,就是缺少spring-cglib-repack-3.1....

    spring3.2.0.m1

    《Spring 3.2.0.M1:框架整合与源码探索》 Spring 3.2.0.M1 是Spring框架的一个重要版本,它在3.x系列中扮演着承上启下的角色,不仅包含了之前版本的功能优化,还引入了一些新的特性和改进。这个版本为开发者提供了...

Global site tag (gtag.js) - Google Analytics