苍穹外卖--springCache-@Cacheable使用

This commit is contained in:
2025-11-24 11:40:15 +08:00
parent 35e93d1449
commit 2125db64f8

View File

@@ -5,6 +5,7 @@ import com.inmind.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@RestController @RestController
@@ -44,7 +45,15 @@ public class UserController {
userMapper.deleteAll(); userMapper.deleteAll();
} }
/*
需求在根据id查询用户时先从redis缓存中查找,如果没有从数据库中查询并将查询到的数据放入redis中
注意Cacheable在方法体执行之前就要获取redis的key值所以不能使用#result
Cacheable底层原理代理对象如果能查询到缓存数据直接就不调用原始方法如果查询不到缓存那就执行原始方法查询数据将查询到的数据保存到
缓存中
*/
@GetMapping @GetMapping
@Cacheable(cacheNames = "userCache",key = "#id")//key的生成 userCache::#id
public User getById(Long id){ public User getById(Long id){
User user = userMapper.getById(id); User user = userMapper.getById(id);
return user; return user;