概念
-
前面使用Spring boot整合的Redis使用Spring Data Redis进行操作,但是代码上还是很复杂,所以我们可以使用Spring Cache框架,对Spring Data Redis的操作进行简化。
-
Spring Cache是一个框架,实现了基于注解的缓存功能,只需要简单地加一个注解,就能实现缓存功能。
-
Spring Cache提供了一层抽象,底层可以切换不同的缓存实现。具体就是通过CacheManager接口来统一不同的缓存技术。
-
CacheManager是Spring提供的各种缓存技术抽象接口
针对不同的缓存技术需要实现不同的CacheManager
CacheManager | 描述 |
---|---|
EhCacheCacheManager | 使用EhCache作为缓存技术 |
GuavaCacheManager | 使用Google的GuavaCache作为缓存技术 |
RedisCacheManager | 使用Redis 作为缓存技术 |
常用注解:
注解 | 说明 |
---|---|
@EnableCaching | 开启缓存注解功能,通常加在启动类上 |
@Cacheable | 在方法执行前先查询缓存中是否有数据,如果有数据,则直接返回缓存数据;如果没有缓存数据,调用方法并将方法返回值放到缓存中 |
@CachePut | 将方法的返回值放到缓存中 |
@CacheEvict | 将一条或多条数据从缓存中删除 |
使用
Spring Cache的Maven坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
<version>2.7.3</version>
</dependency>
想要开启缓存注解
开发,需要在boot的启动类
上添加@EnableCaching
注解
@SpringBootApplication
@EnableCaching
public class Application{
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
然后就可以在Controller相应的方法上添加注解。
添加缓存
在有新增缓存的业务需求时可以使用@CachePut
/**
*CachePut:将方法返回值放入缓存
*value:缓存的名称,每个缓存名称下可以有多个key
*key:缓存的key
*#result.id动态获得返回值的id
*/
@PostMapping
@CachePut(value = "userCache",key = "#result.id")
public User save(User user){
userService.save(user);
return user;
//要将返回user同时添加到缓存中
}
清理缓存
使用@CacheEvict
注解
/**
*此处`key`有很多中写法,意思都是一样的
*/
@CacheEvict(value = "userCache",key = "#id")
//CacheEvict(value = "userCache",key = "#p0")
//CacheEvict(value = "userCache",key = "#root.args[0]")
@DeleteMapping("/{id}")
public void deleteById(@PathVariable Long id){
userService.removeById(id);
}
查询缓存
使用@Cacheable
注解
/*
其中的condition是条件,满足条件时才缓存数据
key可以使用下划线来拼接例如"#user.id"+'_'+"#user.name"
*/
@Cacheable(value = "userCache",key = "#id",condition = "#result != null")
@GetMapping("/{id}")
public User getById(@PathVariable Long id){
User user = userService.getById(id);
return user;
}
总结
使用Redis缓存技术步骤:
- 导maven坐标
导入spring-boot-starter-data-redis和
spring-boot-starter-cache两个坐标 - 配置application.yml
spring:
redis:
host: 127.0.0.1
port: 6379
database: 0
cache:
redis:
time-to-live: 1800000 #设置缓存有效期
- 在启动类添加
@EnableCaching
注解,开启缓存注解功能 - 在Controller的方法上加入@Cacheable、@CacheEvict等注解,及逆行缓存操作