Spring Cache
简化缓存逻辑
使用注解达到缓存
底层可以更换缓存产品
常用注解
@EnableCaching
//开启缓存功能
@Cacheable
//先查看有没有对应缓存,有则直接返回,没有就调用方法然后存入对应缓存
@CachePut
//将方法返回值缓存
@CacheEvict
//删除缓存
下面有2种依赖选择:基础依赖不使用redis,另一个是使用redis的版本
基础依赖(没有redis,使用自带的缓存件):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<scope>compile</scope>
</dependency>
因为一般我们用的基础功能,这个依赖里面的context里就有
与redis捆绑的依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
配置:
spring:
redis:
host: 192.168.199.132
port: 6379
password: "123456"
database: 0
cache:
redis:
time-to-live: 1800000 #缓存有效期 单位:毫秒
cache-null-values: true #设置缓存空值,解决穿透问题
use-key-prefix: true #开启前缀,默认前缀是缓存名
启动类的注解开关:
Controller注入的东西
@CachePut()
放在存储(save)的地方
@CacheEvict()
放在删除(delete),更新(updata)的地方
@Cacheable
放在查询的位置