文章字数:892,阅读全文大约需要3分钟
spring提供了注解形式的缓存,可以在方法查询了一次之后保存结果。但是内部调用不会触发缓存(this.xx())。
基础注解
@Cacheable
被标记方法执行后返回结果会被缓存。@CacheEvict
方法执行前或后执行移除springCache中某些元素。
@Cacheable
标记方法支持缓存,执行一次后返回结果会被保存。拥有三个参数
value
指定缓存在哪个Cache上,指定多个Cache时是一个数组1
2
3
4
5
6
7
8
9"cache1")//Cache是发生在cache1上的 (
public User find(Integer id) {
returnnull;
}
//多个
"cache1", "cache2"})//Cache是发生在cache1和cache2上的 ({
public User find(Integer id) {
returnnull;
}key
缓存的键,需要使用EL表达式。如果不指定,则缺省按照方法的所有参数进行组合1
2
3
4
5
6
7
8
9key="#id"//#参数名 使用参数值作为key
key="#p0"//#p参数的index 使用第一个参数值作为key
//使用spring提供的包含信息的root方法。root.可省略
key="root.methodName"//当前方法名
key="root.method.name"//当前方法
key="root.targetClass"//当前被调用的对象
key="root.targetClass"//对象Class
key="root.args[0]"//当前方法组成的数值
key="root.caches[0].name"//当前被调用的方法使用的Cache拼接:
1
2
3
4"'com:test:'+#id") (key =
//使用全局变量防止多次对key赋值?
public static final String KEY_NAME = "'com:test:'";
"+#id") (key = KEY_NAME +condition
指定发生条件
也是EL表达式1
2condition="#user.id%2==0"
condition = "#key != null"@CachePut
和
@Cacheable
相似,只不过@CachePut
不会检查是否缓存中存在结果,而是直接执行。1
2
3
4
5
6//@CachePut也可以标注在类上和方法上。使用@CachePut时我们可以指定的属性跟@Cacheable是一样的。
"users")//每次都会执行方法,并将结果存入指定的缓存中 (
public User find(User user) {
System.out.println("find user by user " + user);
return user;
}@CacheEvict
用来清除缓存,加在需要清除操作的 方法/类 上。
属性列表:value
、key
、condition
、allEntries
和beforeInvocation
和@Cacheable
相同意义的属性
value
表示清除操作是发生在哪些Cache上的(对应Cache的名称)key
key表示需要清除的是哪个key,如未指定则会使用默认策略生成的keycondition
condition表示清除操作发生的条件
其它属性:
allEntries
allEntries是boolean类型,表示是否需要清除缓存中的所有元素。默认为false,表示不需要。当指定了allEntries为true时,Spring Cache将忽略指定的key。1
2
3
4
5//清除users
"users", allEntries=true) (value=
public void delete(Integer id) {
System.out.println("delete user by id: " + id);
}beforeInvocation
设置
清除默认是方法执行后,如果方法因异常没有成功返回则不会执行清除。设置这个能够在方法执行前清除。1
2
3
4"users", beforeInvocation=true) (value=
public void delete(Integer id) {
System.out.println("delete user by id: " + id);
}@Ehcache
也有设置清除策略
@Caching
@Caching注解可以让我们在一个方法或者类上同时指定多个Spring Cache相关的注解。其拥有三个属性:cacheable、put和evict,分别用于指定@Cacheable、@CachePut和@CacheEvict。
1 | "users"), evict = { ("cache2"), (cacheable = ( |
自定义注解中使用
Spring允许我们在配置可缓存的方法时使用自定义的注解,前提是自定义的注解上必须使用对应的注解进行标注。如我们有如下这么一个使用@Cacheable进行标注的自定义注解。
1 | ({ElementType.TYPE, ElementType.METHOD}) |