Spring Cache

Spring Cache介绍

Spring Cache是一个框架,实现了基于注解的缓存功能,只需要简单加一个注解,就能实现缓存功能。Spring Cache提供了一层抽象,底层可以切换不同的cache实现。具体就是通过CacheManager接口来统一不同的缓存技术。

针对不同的缓存技术需要实现不同的CacheManager:

在这里插入图片描述

Spring Cache常用注解

在这里插入图片描述
在Spring Boot项目中,使用Spring Cache实现缓存功能只需要在项目中导入Spring Cache和相关缓存技术的依赖包即可。

例如,使用Redis作为缓存技术,只需要导入spring-boot-starter-cache和spring-boot-starter-data-redis即可。

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-cache</artifactId>
</dependency>

@CachePut

public @interface CachePut {
  String[] value(); 
  String key() default “” ;
  String condition() default “” ; 
  String unless() default “” ; 
}

value:缓存的名称,相当于一类缓存,如用户的缓存,至于它是哪个(些)用户的缓存就看key的规则了,即每个value下可以拥有多个key。

key:某一类缓存中的数据,比如某个(些)用户缓存数据,而且key能将#result(方法返回值)、#root.methodName(方法名)、#param(方法参数)等作为缓存规则,详情请查看源码。

Condition:满足缓存条件的数据才会放入缓存,condition在调用方法之前和之后都会判断,所以它能使用方法的参数和返回值作为缓存条件

Unless:用于否决缓存更新的,不像condition,该表达只在方法执行之后判断,所以它只能使用方法的返回值作为缓存条件。

缓存条件:Spring Cache支持spEL表达式定义缓存规则。

由于@CachePut的特性,常常在MySQL同步数据到Redis,数据库更新数据时使用@CachePut。

@CacheEvict

public @interface CacheEvict {
  String[] value(); //请参考@CachePut
  String key() default “” ; //请参考@CachePut
  String condition() default “” ; //请参考@CachePut
  boolean allEntries() default false ;      //清除当前value中的所有key,默认false
  boolean beforeInvocation() default false ; //调用方法之前移除,默认false
}

由于@CacheEvict的特性,常常在MySQL同步数据到Redis,数据库删除数据时使用@CacheEvict。

@Cacheable

public @interface Cacheable {
     String[] value();             //请参考@CachePut
     String key() default "" ;      //请参考@CachePut
     String condition() default "" ; //请参考@CachePut
     String unless() default "" ;   //请参考@CachePut
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值