1、Spring Cache介绍
- Spring Cache是一个框架,实现了基于注解的缓存功能,只需要简单地加一个注解,就能实现缓存功能。
- Spring Cache提供了一层抽象,底层可以切换不同的Cache实现。具体就是通过
CacheManager
接口来统一不同的缓存技术。 - CacheManager是Spring提供的各种缓存技术抽象接口
- 针对不同的缓存技术需要实现不同的CacheManager:
CacheManager 描述 EhCacheManager 使用EnCache作为缓存技术 GuavaCacheManager 使用Google的GuavaCache作为缓存技术 RedisCacheManager 使用Redis作为缓存技术
2、Spring Cache常用注解
注解 | 说明 |
---|---|
@EnableCaching | 开启缓存注解功能 |
@CaCheable | 在方法执行前Spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;若没有数据,调用方法并将方法返回值放到缓存中 |
@CachePut | 将方法的返回值放倒缓存中 |
@CacheEvict | 将一条或多条数据从缓存中删除 |
- 在Spring Boot项目中,使用缓存技术只需在项目中导入相关缓存技术依赖包,并在启动类上使用@EnableCaching开启缓存支持即可
- 例如,使用Redis作为缓存技术,只需要导入Spring data Redis的maven坐标即可
3、Spring Cache使用
设置缓存过期时间,如果不设置默认是永久有效
spring:
cache:
redis:
time-to-live: 1800000 #设置缓存数据的过期时间
导入maven坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
实体类需要实现序列化接口(Serializable
)
注入CacheManager
@Autowired
private CacheManager cacheManager;
@Cacheput
/**
* CachePut:将方法返回值放入缓存
* value:缓存的名称,每个缓存的名称下面可以有多个key
* key:缓存的key
* @param user
* @return
*/
@CachePut(value = "userCache",key="#user.id")
@PostMapping
public User save(User user){
userService.save(user);
return user;
}
@CacheEvict
/**
* CacheEvict:清理指定缓存
* value:缓存的名称,每个缓存的名称下面可以有多个key
* key:缓存的key
* @param id
*/
@CacheEvict(value = "userCache",key="#id")
@DeleteMapping("/{id}")
public void delete(@PathVariable Long id){
userService.removeById(id);
}
@Cacheable
/**
* @Cacheable:在方法执行前Spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;若没有数据,调用方法并将方法返回值放到缓存中
* value:缓存的名称,每个缓存的名称下面可以有多个key
* key:缓存的key
* unless:条件,满足条件时才缓存数据
* @param id
* @return
*/
@Cacheable(value = "userCache",key="#id",unless = "#result == null")
@GetMapping("/{id}")
public User getById(@PathVariable Long id){
User user = userService.getById(id);
return user;
}
4、Redis作为缓存产品
在Spring Boot项目中使用Spring Cache的操作步骤(使用Redis缓存技术)
-
导入maven坐标
- spring-boot-starter-data-redis
- spring-boot-starter-cache
<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>
-
配置application.yml
-
在启动类上加入@EnableCaching注解,开启缓存注解功能
-
在Controller的方法上加入@Cacheable、@CacheEvict等注解,进行缓存操作