文章目录
1 Spring Cache 的 简介
Spring 3.1起,提供了基于注解的对Cache的支持。Spring提供了各种xxxCache的实现(如redis缓存)。使用Spring Cache的好处:
-
基于注解,代码清爽简洁
-
可以对缓存进行回滚
-
基于注解也可以实现复杂的逻辑
Spring Cache不是具体的缓存技术,而是基于具体的缓存产品(如Guava、EhCache、Redis等)的共性进行了一层封装,但是可以通过简单的配置切换底层使用的缓存。具体的底层缓存技术究竟采用了Guava、EhCache还是Redis,只需要简单的配置就可以实现方便的切换。
2 Spring Cache的相关配置
2.1 pom文件添加依赖Spring Cache
添加spring cache
的同时也添加redis
的依赖。
<!-- Spring Cache的引入-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- redis依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.2 application.yml
的配置
redis
的安装配置请前往:Linux的常用安装软件(2) ,配置文件的详细数据记得改成自己的。
spring:
redis:
# redis 的 IP 地址
host: 192.168.64.128
# redis的端口
port: 6379
# redis的登录密码
password: czx123
# 使用redis的数据库0
database: 0
jedis:
pool:
max-active: 10
min-idle: 0
max-idle: 8
# 连接超时
timeout: 5000ms
# spring cache的使用
cache:
# 指定使用的缓存类型
type: redis
3 Cache的注解
注解 | 作用 |
---|---|
@CacheEvict | 删除缓存,一般配置在删除,更新,新增方法上面 |
@Cacheable | 应用到读取数据的方法上,即可缓存的方法,如查找方法:先从缓存中读取,如果没有再调用方法获取数据,然后把数据添加到缓存中 |
@EnableCaching | 开启 SpringCache 的默认配置 |
@CacheConfig | 全局Cache配置 |
@CachePut | 将数据放到缓存中,不考虑缓存中有没有,可用于更新或新增方法上 |
3.1 启动类上的注解
在启动类添加@EnableCaching
开启缓存功能,例如:
package com.example;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan