0%

spring缓存

文章字数:892,阅读全文大约需要3分钟

spring提供了注解形式的缓存,可以在方法查询了一次之后保存结果。但是内部调用不会触发缓存(this.xx())。

基础注解

  1. @Cacheable被标记方法执行后返回结果会被缓存。
  2. @CacheEvict方法执行前或后执行移除springCache中某些元素。

@Cacheable

标记方法支持缓存,执行一次后返回结果会被保存。拥有三个参数

  1. value指定缓存在哪个Cache上,指定多个Cache时是一个数组

    1
    2
    3
    4
    5
    6
    7
    8
    9
    @Cacheable("cache1")//Cache是发生在cache1上的
    public User find(Integer id) {
    returnnull;
    }
    //多个
    @Cacheable({"cache1", "cache2"})//Cache是发生在cache1和cache2上的
    public User find(Integer id) {
    returnnull;
    }
  2. key缓存的键,需要使用EL表达式。如果不指定,则缺省按照方法的所有参数进行组合

    1
    2
    3
    4
    5
    6
    7
    8
    9
    key="#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
    @Cacheable(key = "'com:test:'+#id")
    //使用全局变量防止多次对key赋值?
    public static final String KEY_NAME = "'com:test:'";
    @Cacheable(key = KEY_NAME +"+#id")
  3. condition指定发生条件
    也是EL表达式

    1
    2
    condition="#user.id%2==0"
    condition = "#key != null"

    @CachePut

    @Cacheable相似,只不过@CachePut不会检查是否缓存中存在结果,而是直接执行。

    1
    2
    3
    4
    5
    6
    //@CachePut也可以标注在类上和方法上。使用@CachePut时我们可以指定的属性跟@Cacheable是一样的。
    @CachePut("users")//每次都会执行方法,并将结果存入指定的缓存中
    public User find(User user) {
    System.out.println("find user by user " + user);
    return user;
    }

    @CacheEvict

    用来清除缓存,加在需要清除操作的 方法/类 上。

属性列表:valuekeyconditionallEntriesbeforeInvocation
@Cacheable相同意义的属性

  1. value表示清除操作是发生在哪些Cache上的(对应Cache的名称)
  2. keykey表示需要清除的是哪个key,如未指定则会使用默认策略生成的key
  3. conditioncondition表示清除操作发生的条件

其它属性

  1. allEntries allEntries是boolean类型,表示是否需要清除缓存中的所有元素。默认为false,表示不需要。当指定了allEntries为true时,Spring Cache将忽略指定的key。
    1
    2
    3
    4
    5
    //清除users
    @CacheEvict(value="users", allEntries=true)
    public void delete(Integer id) {
    System.out.println("delete user by id: " + id);
    }
  2. beforeInvocation设置
    清除默认是方法执行后,如果方法因异常没有成功返回则不会执行清除。设置这个能够在方法执行前清除。
    1
    2
    3
    4
    @CacheEvict(value="users", beforeInvocation=true)
    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
2
3
4
5
@Caching(cacheable = @Cacheable("users"), evict = { @CacheEvict("cache2"),
@CacheEvict(value = "cache3", allEntries = true) })
public User find(Integer id) {
returnnull;
}

自定义注解中使用

Spring允许我们在配置可缓存的方法时使用自定义的注解,前提是自定义的注解上必须使用对应的注解进行标注。如我们有如下这么一个使用@Cacheable进行标注的自定义注解。

1
2
3
4
5
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Cacheable(value="users")
public @interface MyCacheable {
}