SpringCache
概述


测试
package com.itheima.controller;
import com.itheima.entity.User;
import com.itheima.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
@Autowired
private UserMapper userMapper;
@PostMapping
// @CachePut(cacheNames = "userCache", key="#user.id") // second 1.根据形参来获取每个数据唯一标识【userCache::key作为redis中主键】
// @CachePut(cacheNames = "userCache", key="result.id") // second 2.根据返回值的key作为数据唯一标识
// @CachePut(cacheNames = "userCache", key="#p0.id") // second 3.根据特定参数访问。从零开始访问
// @CachePut(cacheNames = "userCache", key="#a0.id") // second 4.根据特定参数访问。同样从0开始
@CachePut(cacheNames = "userCache", key="#root.args[0].id") // second 5.通过root
public User save(@RequestBody User user){ // 注意:如果查询的id数据库中不存在就会再redis中创建以userCache::key为key,value为null的数据
userMapper.insert(user); // 此时我们再数据库中插入当前id的值,会更新缓存中的数据【将null更新为新插入数据】
return user; // 但是我们跳过程序【将null改为新数据的过程】直接修改数据库中信息并不会更新redis中数据
}
@GetMapping
@Cacheable(cacheNames = "userCache", key = "#id") // 有就加没有就查询数据库再添加到redis
public User getById(Long id){
User user = userMapper.getById(id); // 如果查询的id存在于redis中就不会执行这个方法
return user; // 因为SpringCache会为当前Controller创建一个代理对象,请求这个
} // 代理对象,再代理对象中查询redis,有数据就直接返回。如果将redis中
// 这条数据删除掉就会执行该方法查询数据库中信息
@DeleteMapping
@CacheEvict(cacheNames = "userCache", key = "#id") // 清理缓存,开始就执行还是sql正常执行后执行呢?【先删除数据库信息再删除redis中信息】
public void deleteById(Long id){
userMapper.deleteById(id);
}
@DeleteMapping("/delAll")
@CacheEvict(cacheNames = "userCache", allEntries= true) // 设置当前层的所有数据
public void deleteAll(){ // 对于删除操作都是先删除数据库数据,再删除缓存数据
userMapper.deleteAll();
}
}
918

被折叠的 条评论
为什么被折叠?



