目录
1、springboot 缓存
添加依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
开启springboot缓存
@AuthAccess
@GetMapping("/file/front/all")
@Cacheable(value = "files",key ="'frontAll'")
public Result frontAll() {
return Result.success(fileMapper.selectList(null));
}
@CacheEvict(value = "files",key = "'frontAll'")
@DeleteMapping("/{id}")
public Result delete(@PathVariable Integer id) {
Files files = fileMapper.selectById(id);
files.setIsDelete(true);
return Result.success(fileMapper.updateById(files));
}
@CachePut(value = "files",key = "'frontAll'")
@PostMapping("/update")
public Result update(@RequestBody Files files) {
fileMapper.updateById(files);
return Result.success(fileMapper.selectList(null));
}
2、springboot+redis缓存
redis依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
redis配置
redis:
port: 6379
host: 127.0.0.1
查询缓存
@AuthAccess
@GetMapping("/file/front/all")
// @Cacheable(value = "files",key ="'frontAll'")
public Result frontAll() {
//从缓存获取数据
String jsonStr = stringRedisTemplate.opsForValue().get(FILES_KEY);
List<Files> files = new ArrayList<>();
if (StrUtil.isBlank(jsonStr)){
files = fileMapper.selectList(null);//从数据库取出数据后,刷缓存
stringRedisTemplate.opsForValue().set(FILES_KEY,JSONUtil.toJsonStr(files));
}else {
//从缓存中查询数据
files = JSONUtil.toBean(jsonStr, new TypeReference<List<Files>>() {
},true);
}
return Result.success(files);
}
删除缓存
//删除缓存
private void flushRedis(String key){
stringRedisTemplate.delete(key);
}
更新缓存
//设置缓存
private void setRedis(String key,String value){
stringRedisTemplate.opsForValue().set(key,value);
}
List<Files> files = fileMapper.selectList(null);
setRedis(Constants.FILES_KEY, JSONUtil.toJsonStr(files));