[转载] 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),而是一个对缓存使用的抽象 ...
随机推荐
- 微信小程序验证码获取倒计时
wxml <button disabled='{{disabled}}' bindtap="goGetCode">{{code}}</button> js ...
- 2017百度春招<度度熊买帽子的问题>
题目: 度度熊想去商场买一顶帽子,商场里有N顶帽子,有些帽子的价格可能相同.度度熊想买一顶价格第三便宜的帽子,问第三便宜的帽子价格是多少? 数组中找到第三小的数字 注意边界条件 用STL中的set来 ...
- Leetcode 之Length of Last Word(38)
做法很巧妙.分成左右两个对应的部分,遇到左半部分则入栈,遇到右半部分则判断对应的左半部分是否在栈顶.注意最后要判断堆栈是否为空. bool isValid(const string& s) { ...
- SRM 739 Div.2
250 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <iostre ...
- NOIP 2010
tags: NOIP 并查集 动态规划 搜索 categories: 信息学竞赛 总结 机器翻译 乌龟棋 关押罪犯 引水入城 机器翻译 Solution 维护一个队列, 每次从词典中查词时将单词加入队 ...
- python_day6学习笔记
一.Logger模块 logging.basicConfig函数 可通过具体参数来更改logging模块默认行为,可用参数有 filename: 用指定的文件名创建FiledHandler(后边会具体 ...
- (转) Spring源码阅读 之 Spring整体架构
标签(空格分隔): Spring 声明:本文系转载,原地地址:spring framework 4 源码阅读 Spring骨架 Spring的骨架,也是Spring的核心包.主要包含三个内容 cont ...
- Oracle 通用存储过程
CREATE OR REPLACE PROCEDURE P_Pub_GetList ( StrWhere varchar2, ---查询条件(不带where关键字的查询条件) TableName va ...
- 机器学习方法(七):Kmeans聚类K值如何选,以及数据重抽样方法Bootstrapping
欢迎转载,转载请注明:本文出自Bin的专栏blog.csdn.net/xbinworld. 技术交流QQ群:433250724,欢迎对算法.技术感兴趣的同学加入.我的博客写一些自己用得到东西,并分享给 ...
- npm --save-dev --save 的区别【转载】
源地址:http://blog.csdn.net/juzipchy/article/details/65653683 npm install 在安装 npm 包时,有两种命令参数可以把它们的信息写入 ...