---
title: "spring3 自带 cache 整合之方法缓存"
author: "hoochiang"
date: "2014-09-04T00:55:17Z"
tags: ["Cache", "Spring"]
categories: ["编程语言"]
slug: "spring3-cache"
draft: false
lastmod: "2014-09-04T00:55:17Z"
id: 2113102
url: "https://hoochiang.iteye.com/blog/2113102"
---

spring3 自带 cache 整合之方法缓存 博客分类： spring 最近项目刚好用的spring版本是Spring3.1.M1 ，好像 spring3就开始有了对缓存的整合。其实底层的实现也就是上篇文件一样。http://m635674608.iteye.com/admin/blogs/1678983 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 1 //将缓存保存进andCache，并使用参数中的userId加上一个字符串(这里使用方法名称)作为缓存的key 2 @Cacheable(value="andCache",key="#userId + 'findById'") 3 public SystemUser findById(String userId) { 4 SystemUser user = (SystemUser) dao.findById(SystemUser.class, userId); 5 return user ; 6 } 7 //将缓存保存进andCache，并当参数userId的长度小于32时才保存进缓存，默认使用参数值及类型作为缓存的key 8 @Cacheable(value="andCache",condition="#userId.length &lt; 32") 9 public boolean isReserved(String userId) { 10 System.out.println("hello andCache"+userId); 11 return false; 12 } @CacheEvict 支持如下几个参数： value：缓存位置名称，不能为空，同上 key：缓存的key，默认为空，同上 condition：触发条件，只有满足条件的情况才会清除缓存，默认为空，支持SpEL allEntries：true表示清除value中的全部缓存，默认为false //清除掉指定key的缓存 @CacheEvict(value="andCache",key="#user.userId + 'findById'") public void EvictUserRole(SystemUser user) { System.out.println("hello andCache delete"+user.getUserId()); } //清除掉全部缓存 @CacheEvict(value="andCache",allEntries=true) public final void EvictUsers(String\[] reservedUsers) { System.out.println("hello andCache deleteall"); } Spring3集成了ehcache缓存。 第一步：配置Spring文件，声明支持缓存和支持注解 13 14 20 21 22 23 24 25 28 29 30 32 33 第二步：配置Ehcache文件，定义缓存的具体策略。 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 52 53 54 58 59 60 61 62 第三步：写一个使用缓存的测试方法： 63 import org.springframework.cache.annotation.Cacheable; 64 //将缓存保存进DEFAULT\_CACHE，并使用参数中的userId加上一个字符串(这里使用方法名称)作为缓存的key 65 @Cacheable(value="DEFAULT\_CACHE",key="#userId + 'findById'") 66 public SystemUser findById(String userId) { 67 SystemUser user = (SystemUser) dao.findById(SystemUser.class, userId); 68 return user ; 69 } 70 在这里，value = “”，对应了ehcache中的缓存名。 这种写法spring的缓存框架是根据传入进去的参数来判断查找缓存的，比如这里的param等于“admin”，缓存后，spring在从ehcache查“admin” 从缓存中取了。 如果你想更自主的控制缓存查找，可以使用key参数。 key使用SPEL语言（Spring开发的类似于jsp中的EL表达式的语言）。Key的默认生成如下： 1. 不提供参数，返回0 2. 只提供一个参数，直接返回该参数 3. 提供多个参数，则返回多个参数进行hash运算之后的结果。 总结：其实spring3的这个cache底层的实现就是和这里一样http://m635674608.iteye.com/admin/blogs/1678983 只是spring帮我们封装好了。当然spring封装的还是比较好的。