1.介绍
spring cache(框架)实现了注解的缓存功能,一般在业务层操作。
Spring Cache只是提供了一层抽象,底层可以切换不同的cache实现。具体就是通过CacheManager接口来统一不同的缓存技术。CacheManager是Spring提供的各种缓存技术抽象接口。
| Cachemanger | 描述 |
| EhCacheCacheManager | 使用EhCache作为缓存技术 |
| GuavaCacheManager | 使用Google的GuavaCache作为缓存技术 |
| RedisCacheManager | 使用Redis作为缓存技术 |
2.注解
| @EnableCaching | 开启缓存注解功能(启动类上) |
| @Cacheable | 在方法执行前spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;若没有数据,调用方法并将方法返回值放到缓存中 |
| @CachePut | 将方法的返回值放到缓存中 |
| @CacheEvict | 将一条或多条数据从缓存中删除 |
3.入门案例
3-1导入依赖
在没有导入依赖时:
spring-boot-starter-cache
spring-boot-starter-data-redis
使用默认的ConcurrentHashMap做缓存时,服务重启之后,之前缓存的数据就全部丢失了,在项目中使用,我们会选择使用redis来做缓存。就要导入如上jar包。
3-2配置application.yml
spring:
redis:
host: 192.168.200.200
port: 6379
password: root@123456
database: 0
cache:
redis:
time-to-live: 1800000 #设置缓存过期时间为30分钟,可选
启动类上开启 @EnableCaching注解--缓存功能
//测试一下保存功能
@PostMapping
//@CachePut(value = "userCache", key = "#user.id")
@CachePut(value ="userCache",key = "#result.id")
public User save(User user){
userService.save(user);
return user;
}
//原本的数据中的信息
打开postman
点击send
此时刷新数据中的信息



