铜仁市网站建设_网站建设公司_动画效果_seo优化
2026/1/22 17:44:16 网站建设 项目流程

文章目录

  • 前言
  • 一、@Cacheable 是什么?
  • 二、Springboot 项目中如何使用
    • 2.1 基于内存实现:
      • 2.1.1 Cacheable 引入并使用:
      • 2.1.2 Cacheable 配置参数
    • 2.2 Cacheable 基于redis 缓存
    • 2.3 @Cacheable 注解属性
  • 总结

前言


一、@Cacheable 是什么?

@Cacheable 是 Spring 缓存抽象的核心注解,作用是将方法的返回结果缓存起来:

  • 当第一次调用该方法时,执行方法体并将返回值存入缓存;
  • 后续使用「相同参数」调用时,直接从缓存获取结果,无需执行方法体;
  • 本质是「方法级缓存」,基于「键值对」存储(键:方法名 + 参数;值:方法返回值);
  • 适用场景:查询类方法(如根据 ID 查用户、查商品详情),数据变更频率低、查询频率高。

二、Springboot 项目中如何使用

2.1 基于内存实现:

2.1.1 Cacheable 引入并使用:

(1) 引入缓存依赖
在 pom.xml(Maven)中添加 Spring 缓存启动器(Gradle 同理):

<!-- Spring Cache Starter --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-cache</artifactId></dependency><!-- Caffeine 缓存实现 --><dependency><groupId>com.github.ben-manes.caffeine</groupId><artifactId>caffeine</artifactId></dependency>

(2)开启缓存功能
在 SpringBoot 启动类上添加 @EnableCaching 注解,全局开启缓存支持:

importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;importorg.springframework.cache.annotation.EnableCaching;@SpringBootApplication@EnableCaching// 核心:开启缓存publicclassCacheDemoApplication{publicstaticvoidmain(String[]args){SpringApplication.run(CacheDemoApplication.class,args);}}

(3)在查询方法上添加 @Cacheable
在 Service/Controller 的查询方法上标注 @Cacheable,指定缓存名称(必填):

importorg.springframework.cache.annotation.Cacheable;importorg.springframework.stereotype.Service;@ServicepublicclassUserService{// cacheNames:缓存名称(必填,相当于缓存的“命名空间”)@Cacheable(cacheNames="userCache")publicUsergetUserById(Longid){// 模拟数据库查询(首次调用执行,后续从缓存获取)System.out.println("执行数据库查询,用户ID:"+id);returnnewUser(id,"张三",20);}// 模拟用户实体类(需有 getter/setter,Lombok 可简化)publicstaticclassUser{privateLongid;privateStringname;privateIntegerage;publicUser(Longid,Stringname,Integerage){this.id=id;this.name=name;this.age=age;}// getter/setter 省略(实际开发用 @Data 注解)publicLonggetId(){returnid;}publicStringgetName(){returnname;}publicIntegergetAge(){returnage;}}}

(4) 更新缓存:

// 修改用户后更新缓存(key 需与 @Cacheable 一致)@CachePut(cacheNames="userCache",key="#user.studentId")publicStudentDtoupdateUser(StudentDtouser){System.out.println("更新用户:"+user.getStudentId());returnuser;}

(5) 删除缓存:

// 删除用户后清理缓存@CacheEvict(cacheNames="userCache",key="#id")publicvoiddeleteUser(Stringid){System.out.println("删除用户:"+id);}// 清空整个 userCache 缓存@CacheEvict(cacheNames="userCache",allEntries=true)publicvoidclearUserCache(){System.out.println("清空用户缓存");}

2.1.2 Cacheable 配置参数

spring:cache:type:caffeine# 指定缓存类型为 Caffeine(替代默认的 ConcurrentHashMap/Redis)caffeine:spec:initialCapacity=100,maximumSize=1000,expireAfterWrite=10s# Caffeine 核心参数
  • initialCapacity:缓存初始容量(100):缓存初始化时的容器大小,避免频繁扩容导致性能损耗
  • maximumSize:缓存最大容量(1000):缓存条目数超过 1000 时,会按 LRU 策略淘汰旧数据
  • expireAfterWrite:写入后过期时间(10s):缓存条目创建 / 更新后,10 秒未访问则自动过期

2.2 Cacheable 基于redis 缓存

SpringBoot 默认使用「内存缓存(ConcurrentHashMap)」,重启后缓存丢失,此时可以切换为 Redis:

(1) 引入依赖:

<!-- redis jar--><dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.13.5</version></dependency>

(2)配置项:

spring:cache:type:redisredis:# 1. 全局过期时间(核心,替代 Caffeine 的 expireAfterWrite)time-to-live:1000s# 所有缓存默认 10 秒过期(支持 s/m/h/d)# 3. 是否缓存空值(防止缓存穿透)cache-null-values:true# 4. 缓存 key 前缀(避免不同业务 key 冲突)key-prefix:"cache:"# 5. 是否使用前缀(建议开启)use-key-prefix:truedata:redis:host:localhostport:6379timeout:120000database:1lettuce:pool:max-active:50max-idle:8max-wait:-1min-idle:1

(3) 测试结果:

@Override// 使用缓存@Cacheable(cacheNames="userCache",key="#root.args[0]")publicStudentDtogetStudentById(StringstudentId){log.info("getStudentById:{}",studentId);StudentDtodto=StudentDto.builder().studentId(studentId).studentAge(12).studentName("test").studentSex("man").build();returndto;}

redids 缓存结果

2.3 @Cacheable 注解属性

(1) 注解属性:

@Target({ElementType.METHOD,ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Inherited@Documentedpublic@interfaceCacheable{// 核心属性(按使用频率排序)String[]value()default{};// 等价于 cacheNames,缓存名称(必填)String[]cacheNames()default{};// 缓存名称(必填,和 value 二选一,推荐用这个)Stringkey()default"";// 自定义缓存键(SpEL 表达式)StringkeyGenerator()default"";// 自定义键生成器(与 key 互斥)StringcacheManager()default"";// 指定缓存管理器(多缓存源时用)StringcacheResolver()default"";// 自定义缓存解析器(比 cacheManager 更灵活)Stringcondition()default"";// 缓存条件(满足则缓存,SpEL)Stringunless()default"";// 排除条件(满足则不缓存,SpEL)booleansync()defaultfalse;// 是否同步缓存(解决缓存击穿)}
  • cacheNames: 定义缓存的「命名空间」,区分不同业务的缓存(如用户缓存、订单缓存),必填属性;每个 cacheNames 对应一个独立的缓存容器(如 Caffeine 中的一个 Cache 实例、Redis 中的一个 key 前缀);不能省略,否则 Spring 会抛出「cacheNames/value 不能为空」异常。
  • key(自定义缓存键,SpEL 表达式)自定义缓存的 key,替代默认的「方法名 + 所有参数组合」,灵活控制缓存粒度;默认规则:若不指定 key,Spring 会用 KeyGenerator 生成默认 key(格式:方法全限定名::参数1=值1,参数2=值2);可以使用SpEL 灵活定义缓存的key值

(2) redis key 生成策略:

SpEL 表达式含义示例
#参数名引用方法参数key = “#id”
#参数.属性引用参数对象的属性key = “#user.id”
#result引用方法返回值(仅 condition/unless 生效)key = “#result.id”(不推荐)
#root根对象,包含方法 / 参数等信息key = “#root.methodName + #id”

代码示例:

// 仅以 id 为键(忽略其他参数)@Cacheable(cacheNames="userCache",key="#id")publicUsergetUserById(Longid,StringunusedParam){...}// 以参数对象的属性为键@Cacheable(cacheNames="userCache",key="#user.id + '_' + #user.name")publicUsergetUserByUser(Useruser){...}// 结合根对象:方法名 + 参数(避免不同方法的相同参数冲突)@Cacheable(cacheNames="userCache",key="#root.methodName + '_' + #id")publicUsergetUserById(Longid){...}

(3) 条件控制属性
condition(缓存条件,SpEL 表达式) 作用:仅当表达式结果为 true 时,才将方法结果存入缓存; 执行时机:方法执行后、存入缓存前

// 仅当 id > 0 时缓存(参数条件)@Cacheable(cacheNames="userCache",key="#id",condition="#id > 0")publicUsergetUserById(Longid){...}// 仅当返回值 age > 18 时缓存(返回值条件)@Cacheable(cacheNames="userCache",key="#id",condition="#result.age > 18")publicUsergetUserById(Longid){...}// 多条件组合(参数 id > 0 且返回值不为 null)@Cacheable(cacheNames="userCache",key="#id",condition="#id > 0 and #result != null")publicUsergetUserById(Longid){...}

unless(排除缓存条件,SpEL 表达式)作用:与 condition 相反,当表达式结果为 true 时,不 缓存结果;执行时机:方法执行后、存入缓存前;核心场景:排除 null 值(避免缓存穿透)、排除异常结果等;

// 不缓存 null 值(解决缓存穿透)@Cacheable(cacheNames="userCache",key="#id",unless="#result == null")publicUsergetUserById(Longid){if(id==999L)returnnull;// 不缓存returnnewUser(id,"张三",20);// 缓存}// 不缓存 age <= 18 的用户@Cacheable(cacheNames="userCache",key="#id",unless="#result.age <= 18")publicUsergetUserById(Longid){...}

(4)sync(同步缓存,解决缓存击穿)
作用:开启同步模式,当缓存未命中时,多个并发请求只会有一个请求执行方法体,其余请求等待缓存生成(解决热点 key 缓存击穿);默认值:false(非同步,多个请求同时执行方法体);

// 开启同步缓存,解决缓存击穿@Cacheable(cacheNames="userCache",key="#id",sync=true)publicUsergetUserById(Longid){...}

注意:
① sync=true 时,unless 属性失效(无法基于返回值排除缓存);
② 仅适用于本地缓存(Caffeine),分布式缓存(Redis)需结合分布式锁使用


总结

本文记录Springboot 缓存@Cacheable 的引入和使用。

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询