Spring Cache
Spring Cache是一个框架,实现了基于注解的缓存功能,只需要简单的加一个注解,就能实现缓存功能
Spring Cache提供了一层抽象,底层可以切换不同的缓存实现,例如
1 2 3 4 5
| <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> <version>3.3.1</version> </dependency>
|
在Java中pom.xml导入Redis的客户端maven坐标,Spring Cache会自动识别缓存实现
1 2 3 4
| <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
|
Spring Cache常用注解
| 注解 |
说明 |
| @EnableCaching |
开启缓存注解功能,通常加载启动类上 |
| @Cacheable |
在方法执行前先查询缓存中是否有数据,若有数据,直接返回缓存数据;若无缓存数据,则通过反射调用方法并将方法返回值放到缓存中 |
| @CachePut |
将方法的返回值放到缓存中 |
| @CacheEvict |
将一条或多条数据从缓存中删除 |
具体实现思路
- 导入Spring Cache和Redis相关maven坐标
- 在驱动类上加入@EnableCaching注解,开启缓存注解功能
- 在接口Controller上需要缓存的方法上加入相应注解
1 2 3 4 5 6
| public class CacheDemoApplication { public static void main(String[] args) { SpringApplication.run(CacheDemoApplication.class,args); log.info("项目启动成功..."); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| public class UserController {
@Autowired private UserMapper userMapper;
@PostMapping @CachePut(cacheNames = "userCache",key = "#user.id") public User save(@RequestBody User user){ userMapper.insert(user); return user; }
@DeleteMapping @CacheEvict(cacheNames = "userCache",key="#id") public void deleteById(Long id){ userMapper.deleteById(id); }
@DeleteMapping("/delAll") @CacheEvict(cacheNames = "userCache",allEntries=true) public void deleteAll(){ userMapper.deleteAll(); }
@GetMapping @Cacheable(cacheNames = "userCache",key="#id") public User getById(Long id){ User user = userMapper.getById(id); return user; }
}
|
1 2 3 4 5
| redis: host: localhost port: 6379
|