Spring Cache 常用注解
注解 | 说明 |
@EnableCaching | 开启缓存注解功能 |
@Cacheable | 在方法执行前spring先查看缓存中是否有数据,如果有数据,直接返回缓存数据,若没有,调用方法并将方法返回值放到缓存中。 |
@CachePut | 将方法返回值放到缓存中 |
@CacheEvict | 将一条或多条数据从缓存中删除 |
在spring boot 项目中,使用缓存技术只需要在项目中导入相关依赖包在启动类加入@EnableCaching开启缓存支持。
例如:Redis做缓存技术,导入Spring data Redis的maven 坐标
Spring Cache 使用方式
1. 导入maven坐标
<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. 配置yml
cache:
redis:
time-to-live: 180000 #设置缓存有效期
3.在启动类加入@EnableCaching注解,开启缓存功能
3.在Control的方法上加入@Cacheable、@CacheEvict等注解进行缓存操作
代码示例:
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.entity.User;
import com.itheima.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
@Autowired
private CacheManager cacheManager;
@Autowired
private UserService userService;
/**
* CachePut:将方法返回值放入缓存
* value:缓存名称,每个缓存名称有多个key
* key:缓存的key
*/
@CachePut(value = "userCache",key = "#user.id")
@PostMapping
public User save(User user){
userService.save(user);
return user;
}
@CacheEvict(value = "userCache",key = "#id")
// @CacheEvict(value = "userCache",key = "#p0")
// @CacheEvict(value = "userCache",key = "#root.args[0]")
@DeleteMapping("/{id}")
public void delete(@PathVariable Long id){
userService.removeById(id);
}
// @CacheEvict(value = "userCache",key = "#user.id") //建议使用
// @CacheEvict(value = "userCache",key = "#p0.id")
// @CacheEvict(value = "userCache",key = "#root.args[0]")
@CacheEvict(value = "userCache",key = "#result.id")
@PutMapping
public User update(User user){
userService.updateById(user);
return user;
}
/**
* 在方法执行前spring先查看缓存中是否有数据,如果有数据,直接返回缓存数据,若没有,调用方法并将方法返回值放到缓存中
* value:缓存名称,每个缓存名称有多个key
* key:缓存的key
* condition: 满足条件是才缓存数据
* unless:满足条件不缓存
*/
@Cacheable(value = "userCache",key = "#id",unless = "#result == null ")
@GetMapping("/{id}")
public User getById(@PathVariable Long id){
User user = userService.getById(id);
return user;
}
@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;
}
}