Spring Boot项目@Cacheable注解的使用

@Cacheable 是 Spring 框架中用于缓存的注解之一,它可以帮助你轻松地将方法的结果缓存起来,从而提高应用的性能。下面详细介绍如何使用 @Cacheable 注解以及相关的配置和注意事项。

1. 基本用法

1.1 添加依赖

首先,确保你的项目中包含了 Spring Cache 的依赖。如果你使用的是 Spring Boot,可以在 pom.xmlbuild.gradle 中添加以下依赖:

Maven:

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-cache</artifactId>
</dependency>

Gradle:

implementation 'org.springframework.boot:spring-boot-starter-cache'
1.2 启用缓存

在你的 Spring Boot 应用的主类或配置类上添加 @EnableCaching 注解,以启用缓存功能。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;@SpringBootApplication
@EnableCaching
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}
}
1.3 使用 @Cacheable 注解

假设你有一个服务类 DataService,其中有一个方法 getSortedData 需要缓存其结果。你可以使用 @Cacheable 注解来实现这一点。

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;@Service
public class DataService {@Cacheable("sortedData")public TableDataInfo getSortedData(String param) {// 模拟耗时操作try {Thread.sleep(2000);} catch (InterruptedException e) {Thread.currentThread().interrupt();}// 返回模拟数据return new TableDataInfo();}
}

解释:

  • @Cacheable("sortedData"): 这个注解告诉 Spring 在调用 getSortedData 方法时,先检查名为 sortedData 的缓存中是否存在与参数 param 对应的结果。
    • 如果存在,则直接返回缓存中的结果,不再执行方法体。
    • 如果不存在,则执行方法体,将结果存入缓存中,并返回结果。
1.4 自定义缓存键

默认情况下,Spring 使用方法参数作为缓存键。如果你需要自定义缓存键,可以使用 key 属性。

@Cacheable(value = "sortedData", key = "#param")
public TableDataInfo getSortedData(String param) {// 方法体
}

解释:

  • key = "#param": 使用方法参数 param 作为缓存键。

你还可以使用 SpEL(Spring Expression Language)来构建更复杂的缓存键。

@Cacheable(value = "sortedData", key = "#param + '_' + #anotherParam")
public TableDataInfo getSortedData(String param, String anotherParam) {// 方法体
}

2. 配置缓存管理器

Spring 支持多种缓存实现,如 Caffeine、Ehcache、Redis 等。下面分别介绍如何配置这些缓存管理器。

2.1 使用 Caffeine 作为缓存实现
  1. 添加依赖:

    <dependency><groupId>com.github.ben-manes.caffeine</groupId><artifactId>caffeine</artifactId>
    </dependency>
    
  2. 配置 Caffeine:

    你可以在 application.ymlapplication.properties 中配置 Caffeine 的缓存参数。

    application.yml:

    spring:cache:type: caffeinecaffeine:spec: maximumSize=1000,expireAfterAccess=60s
    

    application.properties:

    spring.cache.type=caffeine
    spring.cache.caffeine.spec=maximumSize=1000,expireAfterAccess=60s
    
    • maximumSize=1000: 设置缓存的最大条目数为 1000。
    • expireAfterAccess=60s: 设置缓存条目在最后一次访问后的过期时间为 60 秒。
2.2 使用 Ehcache 作为缓存实现
  1. 添加依赖:

    <dependency><groupId>org.ehcache</groupId><artifactId>ehcache</artifactId>
    </dependency>
    
  2. 配置 Ehcache:

    创建一个 ehcache.xml 文件,并在其中定义缓存配置。

    ehcache.xml:

    <config xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'xmlns='http://www.ehcache.org/v3'xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core.xsd"><cache alias="sortedData"><key-type>java.lang.String</key-type><value-type>com.ruoyi.common.core.page.TableDataInfo</value-type><resources><heap unit="entries">1000</heap><offheap unit="MB">100</offheap></resources></cache>
    </config>
    
    • <heap unit="entries">1000</heap>: 设置堆内存中缓存的最大条目数为 1000。
    • <offheap unit="MB">100</offheap>: 设置堆外内存中缓存的最大大小为 100MB。
  3. 配置 Spring 使用 Ehcache:

    application.ymlapplication.properties 中指定 Ehcache 配置文件的位置。

    application.yml:

    spring:cache:type: ehcacheehcache:config: classpath:ehcache.xml
    

    application.properties:

    spring.cache.type=ehcache
    spring.cache.ehcache.config=classpath:ehcache.xml
    
2.3 使用 Redis 作为缓存实现
  1. 添加依赖:

    <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    
  2. 配置 Redis:

    application.ymlapplication.properties 中配置 Redis 连接信息。

    application.yml:

    spring:cache:type: redisredis:host: localhostport: 6379
    

    application.properties:

    spring.cache.type=redis
    spring.redis.host=localhost
    spring.redis.port=6379
    
  3. 可选配置:

    你可以进一步配置 Redis 的缓存行为,例如设置最大内存大小和淘汰策略。

    application.yml:

    spring:redis:lettuce:pool:max-active: 20max-idle: 10min-idle: 5timeout: 5000ms
    

3. 其他相关注解

除了 @Cacheable,Spring 还提供了其他几个注解来管理缓存:

3.1 @CachePut

@CachePut 注解用于更新缓存中的值,但不会影响方法的执行。每次调用带有 @CachePut 注解的方法时,都会执行方法体并将结果存入缓存。

@CachePut(value = "sortedData", key = "#param")
public TableDataInfo updateSortedData(String param) {// 更新逻辑return new TableDataInfo();
}
3.2 @CacheEvict

@CacheEvict 注解用于从缓存中移除一个或多个条目。适用于需要清除缓存的情况。

@CacheEvict(value = "sortedData", key = "#param")
public void deleteSortedData(String param) {// 删除逻辑
}// 清除整个缓存
@CacheEvict(value = "sortedData", allEntries = true)
public void clearAllSortedData() {// 清除所有缓存
}
3.3 @Caching

@Caching 注解允许你在同一个方法上组合多个缓存操作。

@Caching(put = {@CachePut(value = "sortedData", key = "#param"),@CachePut(value = "anotherCache", key = "#param")},evict = {@CacheEvict(value = "oldCache", key = "#param")}
)
public TableDataInfo updateAndEvict(String param) {// 更新逻辑return new TableDataInfo();
}

4. 示例代码

下面是一个完整的示例,展示了如何使用 @Cacheable 注解以及配置 Caffeine 缓存。

4.1 项目结构
src
├── main
│   ├── java
│   │   └── com
│   │       └── example
│   │           ├── Application.java
│   │           ├── config
│   │           │   └── CacheConfig.java
│   │           ├── service
│   │           │   └── DataService.java
│   │           └── model
│   │               └── TableDataInfo.java
│   └── resources
│       └── application.yml
4.2 Application.java
package com.example;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;@SpringBootApplication
@EnableCaching
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}
}
4.3 CacheConfig.java
package com.example.config;import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import java.util.concurrent.TimeUnit;@Configuration
@EnableCaching
public class CacheConfig {@Beanpublic CacheManager cacheManager() {CaffeineCacheManager cacheManager = new CaffeineCacheManager("sortedData");cacheManager.setCaffeine(caffeineCacheBuilder());return cacheManager;}Caffeine<Object, Object> caffeineCacheBuilder() {return Caffeine.newBuilder().expireAfterWrite(60, TimeUnit.SECONDS).maximumSize(1000);}
}
4.4 DataService.java
package com.example.service;import com.example.model.TableDataInfo;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;@Service
public class DataService {@Cacheable("sortedData")public TableDataInfo getSortedData(String param) {// 模拟耗时操作try {Thread.sleep(2000);} catch (InterruptedException e) {Thread.currentThread().interrupt();}// 返回模拟数据return new TableDataInfo();}
}
4.5 TableDataInfo.java
package com.example.model;public class TableDataInfo {// 模拟数据模型
}
4.6 application.yml
spring:cache:type: caffeine

5. 注意事项

  1. 缓存一致性:

    • 确保在更新数据时正确使用 @CachePut@CacheEvict 注解,以保持缓存的一致性。
    • 对于分布式系统,考虑使用支持分布式缓存的实现(如 Redis)。
  2. 缓存失效策略:

    • 根据业务需求选择合适的缓存失效策略(如基于时间、基于条件等)。
    • 定期清理过期或不必要的缓存条目,以避免内存泄漏。
  3. 缓存击穿和穿透:

    • 缓存击穿: 当缓存失效后,大量请求同时涌入数据库,导致数据库压力骤增。
      • 解决方案: 可以使用互斥锁(如 Redis 分布式锁)来防止缓存击穿。
    • 缓存穿透: 当查询一个不存在的数据时,所有请求都直接打到数据库。
      • 解决方案: 可以在缓存中存储一个空对象或特殊标记,表示该数据不存在。
  4. 缓存雪崩:

    • 当大量缓存同时失效时,大量请求直接打到数据库,导致数据库压力骤增。
    • 解决方案: 可以设置不同的过期时间,避免缓存同时失效。

6. 调试和监控

为了更好地管理和调试缓存,可以使用以下工具和方法:

  • 日志记录: 在方法上添加日志记录,查看缓存的命中率和缓存操作的频率。
  • 监控工具: 使用监控工具(如 Prometheus、Grafana)来监控缓存的性能指标。
  • Spring Boot Actuator: 提供了缓存相关的端点,可以方便地查看缓存的状态和统计信息。

启用 Spring Boot Actuator:

  1. 添加依赖:

    <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    
  2. 配置暴露端点:

    application.yml:

    management:endpoints:web:exposure:include: "caches"
    
  3. 访问缓存端点:

    访问 http://localhost:8080/actuator/caches 可以查看缓存的状态信息。

总结

通过使用 @Cacheable 注解,可以轻松地在 Spring 应用中实现缓存机制,从而提高应用的性能和响应速度。结合不同的缓存实现(如 Caffeine、Ehcache、Redis),你可以根据具体需求灵活配置缓存策略,确保缓存的有效性和高效性。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/22096.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

windows上vscode cmake工程搭建

安装vscode插件&#xff1a; 1.按装fastc&#xff08;主要是安装MinGW\mingw64比较方便&#xff09; 2.安装C&#xff0c;cmake&#xff0c;cmake tools插件 3.准备工作完成之后&#xff0c;按F1&#xff0c;选择cmake:Quick Start就可以创建一个cmake工程。 4.设置Cmake: G…

SpringMVC详解

文章目录 1 什么是MVC 1.1 MVC设计思想1.2 Spring MVC 2 SpringMVC快速入门3 SpringMVC处理请求 3.1 请求分类及处理方式 3.1.1 静态请求3.1.2 动态请求 3.2 处理静态请求 3.2.1 处理html文件请求3.2.2 处理图片等请求 3.3 处理动态请求 3.3.1 注解说明3.3.2 示例 3.4 常见问题…

【用deepseek和chatgpt做算法竞赛】——还得DeepSeek来 -Minimum Cost Trees_5

往期 【用deepseek和chatgpt做算法竞赛】——华为算法精英实战营第十九期-Minimum Cost Trees_0&#xff1a;介绍了题目和背景【用deepseek和chatgpt做算法竞赛】——华为算法精英实战营第十九期-Minimum Cost Trees_1&#xff1a;题目输入的格式说明&#xff0c;选择了邻接表…

面试题汇总

1. 判断大小端问题 大端&#xff1a;低字节存放在高地址&#xff1b; 小端&#xff1a;低字节存放在低地址 如 : 0x12345678 bool is_little_endian() {unsigned int x 1;return ((char*)&x)[0]; }bool is_big_endian() {unsigned int x 1;return !((char*)&x)[0];…

jsherp importItemExcel接口存在SQL注入

一、漏洞简介 很多人说管伊佳ERP&#xff08;原名&#xff1a;华夏ERP&#xff0c;英文名&#xff1a;jshERP&#xff09;是目前人气领先的国产ERP系统虽然目前只有进销存财务生产的功能&#xff0c;但后面将会推出ERP的全部功能&#xff0c;有兴趣请帮点一下 二、漏洞影响 …

体验用ai做了个python小游戏

体验用ai做了个python小游戏 写在前面使用的工具2.增加功能1.要求增加视频作为背景。2.我让增加了一个欢迎页面。3.我发现中文显示有问题。4.我提出了背景修改意见&#xff0c;欢迎页面和结束页面背景是视频&#xff0c;游戏页面背景是静态图片。5.提出增加更多游戏元素。 总结…

动态存储斐波那契数列(递归优化)

递归 递归是c当中一种自身调用自身的算法。 普通递归解决斐波那契数列问题 #include<iostream> using namespace std; int f(int n){int sum;if(n<2){sum1;}else{sumf(n-1)f(n-2);}return sum; } int main() {int n;cin>>n;cout<<f(n);return 0;}当数据…

php文件上传

文章目录 文件上传机制文件上传脚本文件上传绕过php后缀替换为空web服务器的解析漏洞绕过nginxiisapache 高级文件上传nginx自定义配置文件&#xff08;默认三分钟刷新一次&#xff09;服务端内容检测结合伪协议使用配合日志包含只允许图片上传 上传实战训练 文件上传机制 文件…

播放器系列1——总概述

播放器核心架构 模块解释 文件读取 读取视频文件、读取网络文件、读取音频文件&#xff0c;大概分为这三种&#xff0c;目前代码中仅实现了读取视频文件播放&#xff0c;也就是当没有video数据的时候播放器不可使用。 解复用 容器指的是多媒体文件中的封装格式&#xff0c;…

【存储中间件API】MySQL、Redis、MongoDB、ES常见api操作及性能比较

常见中间件api操作及性能比较 ☝️ MySQL crud操作✌️ maven依赖✌️ 配置✌️ 定义实体类✌️ 常用api ☝️ Redis crud操作✌️ maven依赖✌️ 配置✌️ 常用api ☝️ MongoDB crud操作✌️ maven依赖✌️ 配置文件✌️ 定义实体类✌️ MongoDB常用api ☝️ ES crud操作 ⭐️…

【进程与线程】Linux 线程、同步以及互斥

每个用户进程有自己的地址空间。 线程是操作系统与多线程编程的基础知识。 系统为每个用户进程创建一个 task_struct 来描述该进程&#xff1a;该结构体中包含了一个指针指向该进程的虚拟地址空间映射表&#xff1a; 实际上 task_struct 和地址空间映射表一起用来表示一个进程…

实现动态翻转时钟效果的 HTML、CSS 和 JavaScript,附源码

实现动态翻转时钟效果的 HTML、CSS 和 JavaScript 在现代网页设计中&#xff0c;动画效果可以极大地增强用户体验。本文将介绍如何利用 HTML、CSS 和 JavaScript 创建一个动态翻转时钟的效果&#xff0c;模拟经典机械翻页时钟的视觉效果。我们将通过详细的步骤讲解如何实现时钟…

Spring Boot与MyBatis

Spring Boot与MyBatis的配置 一、简介 Spring Boot是一个用于创建独立的、基于Spring的生产级应用程序的框架&#xff0c;它简化了Spring应用的初始搭建以及开发过程。MyBatis是一款优秀的持久层框架&#xff0c;它支持定制化SQL、存储过程以及高级映射。将Spring Boot和MyBa…

1.16作业

1 进注册界面&#xff0c;第一次以为抓包选把isadmin ture了就好 第二次尝试&#xff0c;勾选is admin&#xff0c;有需要invitecode&#xff08;经典&#xff09; 2 p r**5 r**4 - r**3 r**2 - r 2023 q r**5 - r**4 r**3 - r**2 r 2023 n 25066797992811602609904…

LeetCode 2209.用地毯覆盖后的最少白色砖块:记忆化搜索之——深度优先搜索(DFS)

【LetMeFly】2209.用地毯覆盖后的最少白色砖块&#xff1a;记忆化搜索之——深度优先搜索(DFS) 力扣题目链接&#xff1a;https://leetcode.cn/problems/minimum-white-tiles-after-covering-with-carpets/ 给你一个下标从 0 开始的 二进制 字符串 floor &#xff0c;它表示地…

「正版软件」PDF Reader - 专业 PDF 编辑阅读工具软件

PDF Reader 轻松查看、编辑、批注、转换、数字签名和管理 PDF 文件&#xff0c;以提高工作效率并充分利用 PDF 文档。 像专业人士一样编辑 PDF 编辑 PDF 文本 轻松添加、删除或修改 PDF 文档中的原始文本以更正错误。自定义文本属性&#xff0c;如颜色、字体大小、样式和粗细。…

【报错解决】vue打开界面报错Uncaught SecurityError: Failed to construct ‘WebSocket‘

问题描述&#xff1a; vue运行时正常&#xff0c;但是打开页面后报错 Uncaught SecurityError: Failed to construct WebSocket: An insecure WebSocket connection may not be initiated from a page loaded over HTTPS. 解决方案&#xff1a; 在项目列表中的public下的ind…

骶骨神经

骶骨肿瘤手术后遗症是什么_39健康网_癌症 [健康之路]匠心仁术&#xff08;七&#xff09; 勇闯禁区 骶骨肿瘤切除术

wps中的js开发

严格区分大小写 /*** learn_js Macro*/ function test() {Range(D7).Value2Selection.Value2; // Selection.formula "100" }function Workbook_SheetSelectionChange(Sh, Target) {if(Sh.Name Sheet1) {test();}}function test2() {// 把I4单元格及其周边有数的单…

书生大模型实战营12-InternVL 多模态模型部署微调

文章目录 L2——进阶岛InternVL 部署微调实践0.开发机创建与使用1.环境配置1.1.训练环境配置1.2.推理环境配置 2.LMDeploy部署2.1.LMDeploy基本用法介绍2.2.网页应用部署体验2.3 出错解决2.3.1 问题12.3.2 问题2 3.XTuner微调实践3.1.准备基本配置文件3.2.配置文件参数解读3.3.…