Spring_Cache入门

注解

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

案例

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
   @PostMapping
// @CachePut(cacheNames = "userCache",key = "#result.id" ) 通过返回对象中的id作为key
@CachePut(cacheNames = "userCache",key = "#user.id" )//redis的key值为userCache::user.id
public User save(@RequestBody User user){
userMapper.insert(user);
return user;
}
@Cacheable(cacheNames = "userCache",key = "#id")//如果没数据后通过代理反射调用getById
public User getById(Long id){
User user = userMapper.getById(id);
return user;
}


@DeleteMapping
@CacheEvict(cacheNames = "userCache",key="#id")
public void deleteById(Long id){
userMapper.deleteById(id);
}

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