Files
sky-take-out1103/springcache-demo - inmind/src/main/java/com/inmind/controller/UserController.java

63 lines
2.2 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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.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 LanguageSpEL
*
*/
@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;
}
@DeleteMapping
public void deleteById(Long id){
userMapper.deleteById(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;
}
}