[转载] Spring3.1 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
例如:
- //将缓存保存进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
例如:
- //清除掉指定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 void setReservedUsers() {
- 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的配置
- <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">
之后添加如下声明:
- <!-- 启用缓存注解功能,这个是必须的,否则注解不会生效,另外,该注解一定要声明在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即可,如下:
- <!-- 启用缓存注解功能,这个是必须的,否则注解不会生效,另外,该注解一定要声明在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 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 Cache注解的更多相关文章
- Spring3.1 Cache注解
依赖jar包: <!-- redis --> <dependency> <groupId>org.springframework.data</groupId& ...
- SpringBoot2.0 基础案例(13):基于Cache注解模式,管理Redis缓存
本文源码 GitHub地址:知了一笑 https://github.com/cicadasmile/spring-boot-base 一.Cache缓存简介 从Spring3开始定义Cache和Cac ...
- Spring Boot 2.x基础教程:进程内缓存的使用与Cache注解详解
随着时间的积累,应用的使用用户不断增加,数据规模也越来越大,往往数据库查询操作会成为影响用户使用体验的瓶颈,此时使用缓存往往是解决这一问题非常好的手段之一.Spring 3开始提供了强大的基于注解的缓 ...
- 十二:SpringBoot-基于Cache注解模式,管理Redis缓存
SpringBoot-基于Cache注解模式,管理Redis缓存 1.Cache缓存简介 2.核心API说明 3.SpringBoot整合Cache 3.1 核心依赖 3.2 Cache缓存配置 3. ...
- Spring3.2新注解@ControllerAdvice
Spring3.2新注解@ControllerAdvice @ControllerAdvice,是spring3.2提供的新注解,从名字上可以看出大体意思是控制器增强.让我们先看看@Control ...
- springboot整合redis-sentinel支持Cache注解
一.前提 已经存在一个redis-sentinel集群,两个哨兵分别如下: /home/redis-sentinel-cluster/sentinel-1.conf port 26379 dir &q ...
- Spring的Cache注解
Spring的Cache注解如下所示: @CacheConfig:主要用于配置该类中会用到的一些共用的缓存配置.在这里@CacheConfig(cacheNames = "users&quo ...
- springboot 用redis缓存整合spring cache注解,使用Json序列化和反序列化。
springboot下用cache注解整合redis并使用json序列化反序列化. cache注解整合redis 最近发现spring的注解用起来真的是很方便.随即产生了能不能吧spring注解使用r ...
- spring源码分析之cache注解
Spring 3.1 引入了激动人心的基于注释(annotation)的缓存(cache)技术,它本质上不是一个具体的缓存实现方案(例如EHCache 或者 OSCache),而是一个对缓存使用的抽象 ...
随机推荐
- 用vue实现登录页面
vue和mui一起完成登录页面(在hbuilder编辑器) <!DOCTYPE html> <html> <head> <meta charset=" ...
- strtok的用法(文件操作)
strtok :在一个字符串查找下一个符号 char *strtok( char *strToken, const char *strDelimit ); 返回值:返回指向在strToken字符串找到 ...
- .NET Core 2.0.5安装具体步骤
.NET Core 2.0.5 comprises: .NET Core Runtime 2.0.5 .NET Core SDK 2.1.4 SDK Installer SDK Binaries ...
- Dubbo简单DEMO以及重要配置项
DEMO pom.xml 消费方和服务提供方一致 <properties> <spring.version>4.0.6.RELEASE</spring.version&g ...
- Go语言的指针的一些测试
参考URL: http://ilovers.sinaapp.com/drupal/node/33 1). 指针在 c 中是个重要的东西,& 和 * 一个取地址.一个解析地址,这是 c 的用法, ...
- 【JBPM4】创建流程实例
示例代码: ProcessEngine processEngine = Configuration.getProcessEngine(); ExecutionService executionServ ...
- bzoj 2938 AC自动机 + dfs判环
#include<bits/stdc++.h> #define LL long long #define ll long long #define fi first #define se ...
- shell脚本学习(四)
shell printf命令 printf是shell的另一个输出命令,默认printf不会自动添加换行我们可以手动添加\n. 语法: printf format-string [arguments. ...
- 洛谷P1392 取数 [堆]
题目传送门 取数 题目描述 在一个n行m列的数阵中,你须在每一行取一个数(共n个数),并将它们相加得到一个和.对于给定的数阵,请你输出和前k小的取数方法. 输入输出格式 输入格式: 第一行,三个数n, ...
- redis缓存总结----干货
Redis的概念 Redis是一款内存高速缓存数据库.Redis全称为:Remote Dictionary Server(远程数据服务),Redis是一个key-value存储系统,它支持丰富的数据类 ...