- SpringCache是一个框架,实现了基本注解的缓存功能,只需要简单的添加一个注解,就能实现缓存功能
- SpringCache提供了一层抽象,底层可以切换不同的cache实现,具体就是通过CacheManager接口来统一不同的缓存技术
- CacheManager是Spring提供的各种缓存技术抽象接口
@Autowired
private CacheManager cacheManager;
@EnableCaching
开启缓存注释功能(启动类上)
@CachePut
将方法的返回值放到缓存中
@CacheEvict
清理缓存,将一条或多条数据从缓存中删除
@Cacheable
在方法执行前先查看缓存中是否存在数据,如果有,返回缓存数据,无,则调用方法并将返回值放到缓存中
@CachePut 使用
@CachePut(value = "userCache", key = "#user.id")
@PostMapping
public User save(User user) {
userService.save(user);
return user;
}
@CacheEvict 使用
@CacheEvict(value "userCache", key = "#result.id")
// key = "p0.id/user.id/root.args[0]/id" 也可以
@PutMapping
public User update(User user) {
userService.updateById(user);
return user;
}
@Cacheable 使用
// value缓存名字,如用户缓存,订单缓存
@Cachaable(value = "userCache", key = "#id")
// 或者当user不为空时,才放入缓存中
// @Cachaable(value = "userCache", key = "#id", unless = "#result == null")
@GetMapping("/{id}")
public User getById(@PathVariable Long id) {
User user = userService.getById(id);
return user;
}
以上缓存是在本地实现的,如果想在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>
同时配置yml:
redis:
port: 6379
password: redis密码
database: 0
host: redis服务器地址