CacheManager是Spring提供的各种缓存技术抽象接口。
Spring Cache框架,实现了基于注解的缓存功能,只需要简单地加一个注解,就能实现缓存功能.
Spring Cache提供了一层抽象,底层可以切换不同的cache实现。具体就是通过CacheManager接口来统一不同的缓存技术。
SpirngCache常用注解
在spring boot项目中,使用缓存技术只需在项目中导入相关缓存技术的依赖包,并在启动类上使用@EnableCaching开启缓存支持即可。
例如,使用Redis作为缓存技术,只需要导入Spring data Redis的maven坐标即可。
SpringCache使用redis缓存技术
导入springbootCache和redis maven坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
在yml中配置redis数据源信息和缓存的过期时间(毫秒)
redis:
host: ***.***.***.*** # IP
port: 6379
# password: root
database: 0 # 默认使用 0号db
cache:
redis:
time-to-live: 1800000 # 设置缓存数据的过期时间,30分钟
启动类上加上 @EnableCaching 开启注解缓存
contrller中 请求list,将缓存信息保存redis
@GetMapping("/list") // 在消费者端 展示套餐信息
@Cacheable(value = "setmealCache",key = "#setmeal.categoryId+'_' +#setmeal.status")
delete,add,等方法若数据发生改变了,将缓存移除,重新查询数据库
allEntries默认为 false
@DeleteMapping
@CacheEvict(value = "setmealCache",allEntries = true) // 删除套餐,就要删除套餐相关的所有缓存数据