1. Spring Cache简介
Spring Cache是一个框架,实现了基于注解的缓存功能,只需要简单地加一个注解,就能实现缓存功能。
spring cache 提供了一层抽象,底层可以切换不同的cache实现,具体就是通过CacheManager接口来统一不同的缓存技术。
CacheManager是spring提供的各种缓存技术抽象接口。
针对不同的缓存技术需要实现不同的CacheManager:
CacheManager | 描述 |
EnCacheCacheManager | 使用EhCache作为缓存技术 |
GuavaCacheManager | 使用Google的GuavaCache作为缓存技术 |
RedisCacheManager | 使用Redis作为缓存技术 |
2. Spring Cache常用注解
@EnableCaching | 开启缓存注解功能 | 放在启动类上 |
@Cacheable | 在方法执行前spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;若没有数据,调用方法并将方法返回值放到缓存中。 | 放在方法上 |
@CachePut | 将方法的返回值放到缓存中 | 一般放在新增的方法上 |
@CacheEvict | 将一条或多条数据从缓存中删除 | 放在方法上 |
在springboot项目中,使用缓存技术只需要在项目中导入相关缓存技术的依赖包(例如:使用Redis作为缓存技术,只需要导入Spring data Redis的maven坐标即可),并在启动类上使用@EnableCaching开启缓存支持即可。
@Slf4j
@SpringBootApplication
@EnableCaching
public class CacheDemoApplication {
public static void main(String[] args) {
SpringApplication.run(CacheDemoApplication.class,args);
log.info("项目启动成功...");
}
}
Spring Cache 的基础功能在spring-boot-starter-web中,所以pom文件导入spring-boot-starter-web即可。
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
@Autowired
private CacheManager cacheManager;
@Autowired
private UserService userService;
/**
* CachePut:将方法返回值放入缓存
* value:缓存的名称,每个缓存名称下面可以有多个key
* key:缓存的key
* value是缓存的一个类的名称,key是类中每条数据的key
*/
@CachePut(value = "userCache",key = "#user.id")
@PostMapping
public User save(User user){
userService.save(user);
return user;
}
/**
* CacheEvict:清理指定缓存
* value:缓存的名称,每个缓存名称下面可以有多个key
* key:缓存的key
*/
@CacheEvict(value = "userCache",key = "#p0")
//@CacheEvict(value = "userCache",key = "#root.args[0]")
//@CacheEvict(value = "userCache",key = "#id")
@DeleteMapping("/{id}")
public void delete(@PathVariable Long id){
userService.removeById(id);
}
/**
* 更新数据时要把对应的缓存数据清理掉,分类还是userCache
*/
//@CacheEvict(value = "userCache",key = "#p0.id")
//@CacheEvict(value = "userCache",key = "#user.id")
//@CacheEvict(value = "userCache",key = "#root.args[0].id")
@CacheEvict(value = "userCache",key = "#result.id") //result代表返回结果user
@PutMapping
public User update(User user){
userService.updateById(user);
return user;
}
/**
* Cacheable:在方法执行前spring先查看缓存中是否有数据,如果有数据,
* 则直接返回缓存数据;若没有数据,调用方法并将方法返回值放到缓存中
* value:缓存的名称,每个缓存名称下面可以有多个key
* key:缓存的key
* condition:条件,满足条件时才缓存数据,condition可以使用的对象有root和参数,没有result。所以写condition = "#result != null" 会不起作用
* unless:满足条件则不缓存
*/
@Cacheable(value = "userCache",key = "#id",unless = "#result == null")
@GetMapping("/{id}")
public User getById(@PathVariable Long id){
User user = userService.getById(id);
return user;
}
// 查询条件跟id和name有关系,所以key是拼接的id和name的字符串
@Cacheable(value = "userCache",key = "#user.id + '_' + #user.name")
@GetMapping("/list")
public List<User> list(User user){
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(user.getId() != null,User::getId,user.getId());
queryWrapper.eq(user.getName() != null,User::getName,user.getName());
List<User> list = userService.list(queryWrapper);
return list;
}
}
以上方式的缓存基于内存的ConcurrentHashMap,当服务重启,缓存数据也就会消失,但Redis不会产生该问题。
3. Spring Cache使用方式
在Spring Boot项目中使用Spring Cache的操作步骤:
(1)导入Maven坐标
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>
(2)配置application.yml
spring:
application:
#应用的名称,可选
name: cache_demo
datasource:
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/cache_demo?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
username: root
password: mysq123
redis:
host: 172.17.2.94
port: 6379
# password: root@123456
database: 0
cache:
redis:
time-to-live: 1800000 #设置缓存过期时间,可选,不设置的话永久有效
(3)在启动类上加入@EnableCaching注解,开启缓存注解功能
(4)在Controller的方法上加入@Cacheable、@CacheEvict等注解,进行缓存操作