Spring Cache【Spring Boot】

发布时间 2023-06-26 14:49:56作者: Rover20230226

Spring Cache 是一个框架,实现了基于注解的缓存功能,只需要简单地加一个注解,就能实现缓存功能。【设计思想AOP】

Spring Cache 提供了一层抽象,底层可以切换不同地缓存实现,例如:

  -  EHCache

  -  Caffeine

  -  Redis(常用)

 

Spring Boot 使用缓存常用注解

名称 解释 使用位置
@EnableCaching 开启基于注解地缓存 启动类
@Cacheable

主要针对查询方法配置,在方法执行前先查看缓存中是否有数据,如果有则直接返回;

若没有,调用方法并将方法返回值放到缓存中。

查询方法

@CacheEvict 清空缓存 删除方法
@CachePut 将方法的返回值放到缓存中 新增或修改方法

 

Spring Cache 和 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>