72 lines
2.6 KiB
Java
72 lines
2.6 KiB
Java
package com.inmind.controller;
|
||
|
||
import com.inmind.entity.User;
|
||
import com.inmind.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;
|
||
|
||
|
||
/*
|
||
*
|
||
* 业务:在新增用户时,将用户信息缓存到redis中
|
||
*
|
||
* Spring Expression Language(SpEL)
|
||
*
|
||
*/
|
||
@PostMapping
|
||
// @CachePut(cacheNames = "userCache",key = "#user.id")//如果使用springCache缓存数据,key的生成的规则:userCache::动态ID
|
||
@CachePut(cacheNames = "userCache",key = "#result.id")//对象导航,result就表示该方法的返回值!!!
|
||
// @CachePut(cacheNames = "userCache",key = "#p0.id")//p0:param0 参数列表中第一个参数
|
||
// @CachePut(cacheNames = "userCache",key = "#a0.id")//a0:argment0 参数列表中第一个参数
|
||
// @CachePut(cacheNames = "userCache",key = "#root.args[0].id")//root.args[0]:save方法的参数列表的第0个参数
|
||
public User save(@RequestBody User user){
|
||
userMapper.insert(user);
|
||
return user;
|
||
}
|
||
|
||
/*
|
||
需求:在根据id删除用户时,redis也删除对应的缓存数据@CacheEvict
|
||
|
||
|
||
*/
|
||
@CacheEvict(cacheNames = "userCache",key = "#id")//key的生成 userCache::#id
|
||
@DeleteMapping
|
||
public void deleteById(Long id){
|
||
userMapper.deleteById(id);
|
||
}
|
||
|
||
//allEntries = true:以cacheNames开头的所有的键,全部删除(userCache::*)
|
||
@CacheEvict(cacheNames = "userCache",allEntries = true)//key的生成 userCache::#id
|
||
@DeleteMapping("/delAll")
|
||
public void deleteAll(){
|
||
userMapper.deleteAll();
|
||
}
|
||
|
||
/*
|
||
需求:在根据id查询用户时,先从redis缓存中查找,如果没有从数据库中查询,并将查询到的数据放入redis中
|
||
注意:Cacheable在方法体执行之前就要获取redis的key值,所以不能使用#result
|
||
|
||
Cacheable底层原理:代理对象,如果能查询到缓存数据,直接就不调用原始方法,如果查询不到缓存,那就执行原始方法,查询数据,将查询到的数据保存到
|
||
缓存中
|
||
*/
|
||
@GetMapping
|
||
@Cacheable(cacheNames = "userCache",key = "#id")//key的生成 userCache::#id
|
||
public User getById(Long id){
|
||
User user = userMapper.getById(id);
|
||
return user;
|
||
}
|
||
|
||
}
|