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注解
相关推荐
练习时长一年2 分钟前
AopAutoConfiguration源码阅读
java·spring boot·intellij-idea
源码宝1 小时前
【智慧工地源码】智慧工地云平台系统,涵盖安全、质量、环境、人员和设备五大管理模块,实现实时监控、智能预警和数据分析。
java·大数据·spring cloud·数据分析·源码·智慧工地·云平台
David爱编程2 小时前
面试必问!线程生命周期与状态转换详解
java·后端
J_bean2 小时前
Spring AI Alibaba 项目接入兼容 OpenAI API 的大模型
人工智能·spring·大模型·openai·spring ai·ai alibaba
LKAI.3 小时前
传统方式部署(RuoYi-Cloud)微服务
java·linux·前端·后端·微服务·node.js·ruoyi
HeyZoeHey3 小时前
Mybatis执行sql流程(一)
java·sql·mybatis
2301_793086873 小时前
SpringCloud 07 微服务网关
java·spring cloud·微服务
柳贯一(逆流河版)4 小时前
Spring 三级缓存:破解循环依赖的底层密码
java·spring·缓存·bean的循环依赖
该用户已不存在5 小时前
OpenJDK、Temurin、GraalVM...到底该装哪个?
java·后端
TT哇6 小时前
@[TOC](计算机是如何⼯作的) JavaEE==网站开发
java·redis·java-ee