Spring Cache

Spring Cache是一个框架,实现了基于注解的缓存功能,只需要简单的加一个注解,就能实现缓存功能

Spring Cache提供了一层抽象,底层可以切换不同的缓存实现,例如

  • EHCache
  • Caffeine
  • Redis
1
2
3
4
5
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
<version>3.3.1</version>
</dependency>

在Java中pom.xml导入Redis的客户端maven坐标,Spring Cache会自动识别缓存实现

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

Spring Cache常用注解

注解 说明
@EnableCaching 开启缓存注解功能,通常加载启动类上
@Cacheable 在方法执行前先查询缓存中是否有数据,若有数据,直接返回缓存数据;若无缓存数据,则通过反射调用方法并将方法返回值放到缓存中
@CachePut 将方法的返回值放到缓存中
@CacheEvict 将一条或多条数据从缓存中删除

具体实现思路

  • 导入Spring Cache和Redis相关maven坐标
  • 在驱动类上加入@EnableCaching注解,开启缓存注解功能
  • 在接口Controller上需要缓存的方法上加入相应注解
1
2
3
4
5
6
public class CacheDemoApplication {
public static void main(String[] args) {
SpringApplication.run(CacheDemoApplication.class,args);
log.info("项目启动成功...");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public class UserController {

@Autowired
private UserMapper userMapper;

@PostMapping
@CachePut(cacheNames = "userCache",key = "#user.id")//使用spel spring EL //如果使用Spring Cache缓存数据,key的生成为 userCache::1
//@CachePut(cacheNames = "userCache",key = "#result.id")// . 为对象导航
//@CachePut(cacheNames = "userCache",key = "#p0.id") //0,取第一个参数
//@CachePut(cacheNames = "userCache",key = "#a0.id")
//@CachePut(cacheNames = "userCache",key = "#root.args[0].id")
public User save(@RequestBody User user){
userMapper.insert(user);
return user;
}

@DeleteMapping
@CacheEvict(cacheNames = "userCache",key="#id")//key的生成: userCache::1 id为1就为1
public void deleteById(Long id){
userMapper.deleteById(id);
}

@DeleteMapping("/delAll")
@CacheEvict(cacheNames = "userCache",allEntries=true)
public void deleteAll(){
userMapper.deleteAll();
}

@GetMapping
@Cacheable(cacheNames = "userCache",key="#id")//key的生成: userCache::1 id为1就为1
public User getById(Long id){
User user = userMapper.getById(id);
return user;
}

}
1
2
3
4
5
  redis:
host: localhost
port: 6379
# password: 123456
# database: 1