Spring Cache 是Spring - context-xxx.jar中提供的功能,可以结合EHCache,Redis等缓存工具使用。给用户提供非常方便的缓存处理,缓存基本判断等操作,可以直接使用注解实现。
在包含了Spring - context-xxx.jar的Spring Boot项目中,在启动类中添加@EnableCaching注解,即可开启缓存功能。默认Spring Cache是不开启。
开发简单,基于注解实现缓存管理。
以查询逻辑举例。流程如下:
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-pJL9Je4Z-1662388941403)(images/1.png)]](https://1000bd.com/contentImg/2023/10/29/144031778.png)
在代码方法中编写对数据库的访问。只需要完成上面流程图中“从mysql取出”部分的代码。剩余事情使用一个非常简单的注解即可,省略了访问redis取数据及把mysql数据缓存到redis的代码,让开发起来更简单。
流程死板。以查询逻辑举例,也就是@Cacheable注解流程:
基于上述原因,现在在商业项目开发中,很少使用Spring Cache直接管理缓存。只有流程死板,缓存时间固定的数据,可以考虑使用Spring Cache。
只要检测到项目中配置了下面缓存工具(导入了依赖,在Spring容器中发现对应工具的内容),无论导入多少个缓存工具依赖,只用优先级最高的一个。
默认寻找缓存工具的顺序:(为什么Redis配置上就可以用的原因)
创建测试工程
添加Spring-boot-starter-web会包含spring-context。就可以使用Spring Cache了。
spring-boot-start-data-redis 添加后会有Redis配置环境,当前项目没有添加其他缓存工具,所以Spring Cache会使用Redis作为缓存工具。
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.3.12.RELEASEversion>
parent>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-redisartifactId>
dependency>
dependencies>
新建application.yml
spring:
redis:
host: 192.168.8.128
port: 6379 # 默认值,可省略
@SpringBootApplication
@EnableCaching
public class SpringCacheApplication {
public static void main(String[]