springboot 使用 SpringCache(二)

上篇基本上了解了SpringCache,这一篇讲一下springcache的参数

1. @Cacheable

@Cacheable可以标记在一个方法上,也可以标记在一个类上。当标记在一个方法上时表示该方法是支持缓存的,当标记在一个类上时则表示该类所有的方法都是支持缓存的。

@Cacheable可以指定三个属性,valuekeycondition

== 1.value:==
指定cache名称。
== 2.key:==
key和key-value对中的键相同,它支持springEL表达式,
它分为两种策略:默认策略和自定义策略,当我们没有指定该属性时,Spring将使用默认策略生成key .

默认策略

  1. 如果方法没有参数,则使用0作为key。

  2. 如果只有一个参数的话则使用该参数作为key。

  3. 如果参数多余一个的话则使用所有参数的hashCode作为key。

自定义策略:使用SpringEL表达式

   @Cacheable(value="users", key="#id")
   public User find(Integer id) {
      return null;
   }
 @Cacheable(value="users", key="#user.id")
   public User find(User user) {
      returnnull;
   }

上面两个例子分别是使用id和user.id作为键

除了上述使用方法参数作为key之外,Spring还为我们提供了一个root对象可以用来生成key。通过该root对象我们可以获取到以下信息。
在这里插入图片描述
当我们要使用root对象的属性作为key时我们也可以将“#root”省略,因为Spring默认使用的就是root对象的属性。如:

   @Cacheable(value={"users", "xxx"}, key="caches[1].name")
   public User find(User user) {
      returnnull;
   }

== 3.condition==

有的时候我们可能并不希望缓存一个方法所有的返回结果。通过condition属性可以实现这一功能。condition属性默认为空,表示将缓存所有的调用情形。其值是通过SpringEL表达式来指定的,当为true时表示进行缓存处理;当为false时表示不进行缓存处理,即每次调用该方法时该方法都会执行一次。如下示例表示只有当user的id为偶数时才会进行缓存。

   @Cacheable(value={"users"}, key="#user.id", condition="#user.id%2==0")
   public User find(User user) {
      System.out.println("find user by user " + user);
      return user;
   }

2. @CachePut

对于使用@Cacheable标注的方法,Spring在每次执行前都会检查Cache中是否存在相同key的缓存元素,如果存在就不再执行该方法,而是直接从缓存中获取结果进行返回,否则才会执行并将返回结果存入指定的缓存中。

使用@CachePut时我们可以指定的属性跟@Cacheable是一样的

3.@cacheEvict

@CacheEvict可以指定的属性有value、key、condition、allEntries和beforeInvocation。其中value、key和condition的语义与@Cacheable对应的属性类似。

1. allEntries
allEntries是boolean类型,表示是否需要清除缓存中的所有元素。默认为false,表示不需要。当指定了allEntries为true时,Spring Cache将忽略指定的key。有的时候我们需要Cache一下清除所有的元素,这比一个一个清除元素更有效率。

      @CacheEvict(value="users", allEntries=true)
   public void delete(Integer id) {
      System.out.println("delete user by id: " + id);
   }

2.beforeInvocation
清除操作默认是在对应方法成功执行之后触发的,即方法如果因为抛出异 常而未能成功返回时也不会触发清除操作。使用beforeInvocation可以改变触发清除操作的时间,当我们指定该属性值为true时,Spring会在调用该方法之前清除缓存中的指定元素。

@CacheEvict(value="users", beforeInvocation=true)
   public void delete(Integer id) {
      System.out.println("delete user by id: " + id);
   }

4.@Caching

@Caching注解可以让我们在一个方法或者类上同时指定多个Spring Cache相关的注解。其拥有三个属性:cacheable、put和evict,分别用于指定 @Cacheable、@CachePut和@CacheEvict

   @Caching(cacheable = @Cacheable("users"), evict = { @CacheEvict("cache2"),
         @CacheEvict(value = "cache3", allEntries = true) })
   public User find(Integer id) {
      returnnull;
   }
发布了33 篇原创文章 · 获赞 1 · 访问量 2052

猜你喜欢

转载自blog.csdn.net/m0_45025658/article/details/104240192