SpringBoot缓存注解利用

[复制链接]
发表于 2026-2-19 09:54:17 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
配景

除了 RedisTemplate 外,  自Spring3.1开始,Spring自带了对缓存的支持。我们可以直接利用Spring缓存技能将某些数据放入本机的缓存中;Spring缓存技能也可以搭配其他缓存中央件(如Redis等)进利用用,将某些数据写入到缓存中央件(缓存中央件大概在其他呆板上)中。
常用缓存


  • @EnableCaching: 开启缓存注解功能,通常加在启动类上
  • @Cacheable: 在方法实行前先查询缓存中是否有数据,假如有数据,则直接返回缓存数据,假如没有缓存数据,调用方法并将方法返回值放到缓存中。
  • @CachePut: 将方法的返回值放到缓存中。
  • @CacheEvit: 将一条大概多条数据从缓存中删除。
利用

1. 添加依靠并设置redis信息

在 pom.xml 中添加依靠
  1. <dependency>
  2.     <groupId>org.springframework.boot</groupId>
  3.     <artifactId>spring-boot-starter-cache</artifactId>
  4. </dependency>
复制代码
在 application.yml 文件中添加依靠
  1. spring:
  2.   redis:
  3.     host: 192.168.**.***
  4.     port: ****
  5.     password: ****
  6.     database: 1
复制代码
2. 在启动类上添加 @EnableCaching 注解


3. 利用缓存注解
  1. package com.itheima.controller;
  2. @RestController
  3. @RequestMapping("/user")
  4. @Slf4j
  5. public class UserController {
  6.     @Autowired
  7.     private UserMapper userMapper;
  8.     @PostMapping
  9.     // 使用 @CachePut 添加缓存数据, key 的生成: userCache::user.id,例如 userCache::12
  10.     @CachePut(cacheNames = "userCache", key = "#user.id")
  11.     public User save(@RequestBody User user){
  12.         userMapper.insert(user);
  13.         return user;
  14.     }
  15.     @DeleteMapping
  16.     // 删除指定缓存
  17.     @CacheEvict(cacheNames = "userCache", key = "#id")
  18.     public void deleteById(Long id){
  19.         userMapper.deleteById(id);
  20.     }
  21.         @DeleteMapping("/delAll")
  22.     // 删除所有缓存
  23.     @CacheEvict(cacheNames = "userCache", allEntries = true)
  24.     public void deleteAll(){
  25.         userMapper.deleteAll();
  26.     }
  27.     @GetMapping
  28.     // key 的生成: userCache::12
  29.     @Cacheable(cacheNames = "userCache", key = "#id")
  30.     public User getById(Long id){
  31.         User user = userMapper.getById(id);
  32.         return user;
  33.     }
  34. }
复制代码
4. 结果

这里以 @CachePut 注解为例演示结果。
向表中添加数据后可以看到乐成将新用户信息添加到了缓存中。

缓存中信息

回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表