💥 该系列属于【SpringBoot基础】专栏,如您需查看其他SpringBoot相关文章,请您点击左边的连接
目录
一、Spring Cache
1. 简介
Spring Cache是Spring框架提供的一个抽象缓存框架,它简化了在Spring应用中缓存数据的操作。Spring Cache的目标是提供一种通用的缓存抽象,使得开发者可以透明地使用缓存,而无需关心底层缓存的实现细节。
Spring Cache 提供了一层抽象,底层可以切换不同的缓存实现,例如:
- EHCache
- Caffeine
- Redis
2. 常用注解
二、项目准备
1. 添加依赖
<!-- 添加 spring cache 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
<version>2.7.3</version>
</dependency>
2. 配置文件
server.port=8080
mybatis-plus.mapper-locations=classpath:mappers/*xml
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=your_password
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.database=1
3. 数据库
添加一个名为test的数据库,表单名字为person,字段如下:
4. 启动类
加上缓存注解@EnableCaching ,才能使用Spring Cache
@EnableCaching //开启缓存注解
@SpringBootApplication
public class SpringCachedemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringCachedemoApplication.class, args);
}
}
5. 利用MyBatisPlus插件生成代码
项目结构如下:
三、基本操作
1. @CachePut
(1)controller
@RestController
@RequiredArgsConstructor
public class PersonController {
private final IPersonService personService;
@RequestMapping("/insert")
@CachePut(cacheNames = "personCache" ,key = "#p.id") //personCache::#p.id
public Person insert(@RequestBody Person p) {
personService.save(p);
//插入到SQL数据库的同时,还要把方法的返回值p保存到Redis
return p;
}
}
(2)测试
Redis缓存:
MySQL数据库:
2. @Cacheable
(1)controller
@RequestMapping("/getById")
@Cacheable(cacheNames = "personCache" ,key = "#id") //personCache::#id
public Person getById(Integer id) {
System.out.println("该getById函数体执行了");
//先从Redis缓存中查找,如果没有再从SQL数据库中查找,并把查询结果存入Redis缓存中
return personService.getById(id);
}
(2)测试1
控制台没有打印"该getById函数体执行了",说明函数内部没有执行,底层是基于动态代理技术实现的。
(3)测试2
现在手动把Redis中id为2的person删除,删除结果如下:
查询id为2的person
控制台打印:
该getById函数体执行了
缓存结果:
3. @CacheEvict删除一条数据
(1)controller
@RequestMapping("/deleteById")
@CacheEvict(cacheNames = "personCache" ,key = "#id") //personCache::#id
public void deleteById(Integer id) {
//根据id移除数据库的person,同时也移除缓存中的person
personService.removeById(id);
}
(2)测试
数据库:
缓存结果:
4. @CacheEvict删除该目录下所有数据
(1)controller
@RequestMapping("/deleteAll")
@CacheEvict(cacheNames = "personCache" ,allEntries = true) //personCache::#id
public void deleteById() {
//移除数据库所有的person,同时也移除缓存中所有的person
personService.removeAll();
}
(2)mapper
@Delete("DELETE FROM person")
void removeAll();
(3)测试
数据库:
缓存结果: