Spring Cache框架(缓存)

1、介绍:

Spring Cache 是一个框架,实现了基于注解的缓存功能,只需要简单加个注解,就能实现缓存功能。它提供了一层抽象,底层可以切换不同的cache实现。具体就是通过CacheManager 接口来实现不同的缓存技术。

针对不同的混存技术需要实现不同的CacheManager:

CacheManager 描述
EhCacheCacheManager 使用EhCache作为缓存技术
GuavaCacheManager 使用Google的GuavaCache作为缓存技术
RedisCacheManager 使用Redis作为缓存技术

2、Spring Cache常用注解

注解 说明
@EnableCaching 开启缓存注解功能
@Cacheable 在方法执行前spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;若没有数据,调用方法并将方法返回值放到缓存中
@CachePut 将方法的返回值放到缓存中
@CacheEvict 将一条或者多条数据从缓存中删除

在spring boot项目中,使用缓存技术只需要导入相关缓存技术的依赖包,并在启动类上使用@EnableCaching开启缓存支持即可。例如,使用Redis作为缓存技术,只需要导入Spring Data Redis的maven坐标即可。

java 复制代码
比如此处@CachePut使用例子
@CachePut(value = "name",key = "#result.id")//将方法返回值放入缓存 ,SpEL方法格式获得数据
publie User save(User user){
  userService.save(user);
  return user;
  }
 //此处value就是缓存的名称,每个缓存下面可以有多个key
 //key:缓存的key
java 复制代码
//清理指定缓存
@CacheEvict(value = "userCache",key ="#p0")//或者
@CacheEvict(value = "userCache",key ="#root.args[0]")
@CacheEvict(value = "userCache",key ="#id")
@DeleteMapping("/{id}")
public void delete(@PathVariable Long id) {
 userService.removeById(id);
 }
java 复制代码
@Cacheable(value = "userCache" ,key = "#id",condition = "#result != null")
@GetMapping("/{id}")
public User getById(@PathVariable Long id) {
User user = userService.getById(id);
//此时有缓存则直接返回数据,不会进入该方法
//当id查询为空时,也会返回null数据当做缓存,此时需要加@Cacheable中方法condition条件,返回值不为空时加入缓存
//(unless = "#result == null"),返回值为空时不缓存
 return user;
}
java 复制代码
@GetMapping("/list")
@Cacheable(value = "userCache",key = "#user.id +'_'+#user.name")
public List<User> list (User user) {
  LambdaQueryWrapper <user> queryWrapper = new LambdaQueryWrapper<>();
  queryWrapper.eq(user.getId() != null,User::getId,user.getId());
  queryWrapper.eq(user.getName() != null,User::getName,user.getName());
  List<User> list = userService.list(querryWrapper):
  return list;
}

底层基于Map来实现的,此时重启服务,缓存都会消失,下面使用Redis来做缓存技术;配置文件需要配置redis的cache同时可配置缓存有效期time-to-live。

java 复制代码
具体实现思路
1、导入Spring Cache 和 Redis 相关 maven坐标
2、在application.yml中配置缓存数据的过期时间
3、在启动类上加@EnableCaching注解,开启缓存注解功能
4、在查询方法上加入@Cacheable注解
5、在修改保存方法上加入@CacheEvict注解
相关推荐
pianmian11 小时前
类(JavaBean类)和对象
java
我叫小白菜2 小时前
【Java_EE】单例模式、阻塞队列、线程池、定时器
java·开发语言
Albert Edison2 小时前
【最新版】IntelliJ IDEA 2025 创建 SpringBoot 项目
java·spring boot·intellij-idea
超级小忍3 小时前
JVM 中的垃圾回收算法及垃圾回收器详解
java·jvm
weixin_446122463 小时前
JAVA内存区域划分
java·开发语言·redis
勤奋的小王同学~3 小时前
(javaEE初阶)计算机是如何组成的:CPU基本工作流程 CPU介绍 CPU执行指令的流程 寄存器 程序 进程 进程控制块 线程 线程的执行
java·java-ee
TT哇3 小时前
JavaEE==网站开发
java·redis·java-ee
2401_826097623 小时前
JavaEE-Linux环境部署
java·linux·java-ee
缘来是庄4 小时前
设计模式之访问者模式
java·设计模式·访问者模式
Bug退退退1234 小时前
RabbitMQ 高级特性之死信队列
java·分布式·spring·rabbitmq