Spring Cache
简介
Spring Cache是一个框架,实现了基于注解的缓存功能,只需要简单地加一个注解,就能实现缓存功能。
Spring Cache:提供了一层抽象,底层可以切换不同的cache实现。具体就是通过CacheManager接口来统一不同的缓
存技术。
CacheManager是Spring提供的各种缓存技术抽象接口。
针对不同的缓存技术需要实现不同的CacheManager:
CacheManager | 描述 |
---|---|
EhCacheCacheManager | 使用EhCache作为缓存技术 |
GuavaCacheManager | 使用Googlel的GuavaCache作为缓存技术 |
RedisCacheManager | 使用Redis作为缓存技术 |
常用注解
注解 | 说明 |
---|---|
@EnableCaching | 开启缓存注解功能 |
@Cacheable | 在方法执行前spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据 若没有数据,调用方法并将方法返回值放到缓存中 |
@CachePut | 将方法的返回值放到缓存中 |
@CacheEvict | 将一条或多条数据从缓存中删除 |
在spring boot项目中,使用缓存技术只需在项目中导入相关缓存技术的依赖包(web-starter自带有一些实现类),并在启动类上使用
@EnableCaching开启缓存支持即可。
例如,使用Redis作为缓存技术,只需要导入Spring data Redis的maven坐标即可。
属性: * value:缓存的名称,每个缓存名称下面可以有多个key * key:缓存的key * condition:条件,满足条件时才缓存数据 * unless:满足条件则不缓存
使用Redis作为缓存技术
-
导入maven坐标
<!-- 拓展缓存技术的整合 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <!-- 含RedisCacheManager --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
-
配置yml文件
spring: redis: host: localhost port: 6379 # password: root@123456 database: 0 cache: redis: time-to-live: 1800000 #设置缓存过期时间,可选
-
@EnableCaching开启缓存支持