Spring Cache
1、Spring Cache 介绍
Spring Cache
是一个框架,实现了基于注解的缓存功能,只需要简单地加一个注解,就能实现缓存功能。
Spring Cache 提供了一层抽象,底层可以切换不同的 cache 实现。具体就是通过 CacheManager
接口来同意不同的缓存技术。
CacheManager 是 Spring 提供的各种缓存技术抽象接口。
针对不同的缓存技术需要实现不同的 CacheManger:
CacheManager | 描述 |
---|---|
EhCacheCacheManager | 使用 EhCache 作为缓存技术 |
GuavaCacheManager | 使用 Google 的 GuavaCache 作为缓存技术 |
RedisCacheManager | 使用 Redis 作为缓存技术 |
2、Spring Cache 常用注解
注解 | 说明 |
---|---|
@EnableCaching | 开启缓存注解功能 |
@Cacheable | 在方法执行前spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据; 若没有数据,调用方法并将方法返回值放到缓存中 |
@CachePut | 将方法的返回值放到缓存中 |
CacheEvict | 将一条或多条数据从缓存中删除 |
在SpringBoot项目中,使用缓存技术只需在项目中导入相关缓存技术的依赖包,并在启动类上使用 @EnableCaching
开启缓存支持即可。
例如,使用Redis作为缓存技术,只需要导入 Spring data Redis
的 Maven 坐标即可。
3、Spring Cache 使用方式
在 SpringBoot 项目中使用 Spring Cache 的操作步骤(使用 Redis 缓存技术):
-
导入 Maven 坐标
spring-boot-starter-data-redis spring-boot-starter-cache
-
配置
application.yml
spring: cache: redis: time-to-live: 1800000 # 设置缓存有效期
-
在启动类上加入
@EnableCaching
注解,开启缓存注解功能 -
在 Controller 的方法上加入
@Cacheable
、@CacheEvict
、等注解,进行缓存操作/** * CachePut 将方法的返回值放入缓存 * CacheEvict 删除指定缓存 * Cacheable: 在方法执行前spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;若没有数据,调用方法并将方法返回值放到缓存中 * value:缓存的名称 * key:缓存的key * condition:条件-> 满足指定条件才缓存数据 * unless:条件-> 不满足条件才缓存数据 */