Spring框架如何做EhCache緩存?

在Spring框架中,緩存是一種常見的優化手段,用于減少對數據庫或其他資源的訪問次數,從而提高應用性能。Spring提供了強大的緩存抽象,支持多種緩存實現(如EhCache、Redis、Caffeine等),并可以通過注解或編程方式輕松集成。

本文以EhCache為例,來演示Spring框架如何做緩存。以下是Spring實現EhCache緩存的實現方式和步驟:

1、引入緩存依賴

pom.xml中添加EhCache相應的依賴:

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

2、配置緩存管理器

在Spring Boot中,可以通過配置類來定義緩存管理器。以下是一些EhCache緩存實現的配置示例:

package com.config;import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;@Configuration
@EnableCaching // 啟用Spring緩存支持
public class CacheConfig {@Beanpublic EhCacheManagerFactoryBean ehCacheManagerFactoryBean() {EhCacheManagerFactoryBean bean = new EhCacheManagerFactoryBean();bean.setConfigLocation(new ClassPathResource("ehcache.xml")); // 指定配置文件路徑bean.setShared(true); // 共享EhCache實例return bean;}@Beanpublic CacheManager cacheManager() {return new EhCacheCacheManager(ehCacheManagerFactoryBean().getObject());}
}

3、配置ehcache.xml文件

需要在src/main/resources目錄下創建ehcache.xml配置文件:

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"><diskStore path="java.io.tmpdir"/><defaultCachemaxElementsInMemory="10000"eternal="false"timeToIdleSeconds="120"timeToLiveSeconds="120"overflowToDisk="false"memoryStoreEvictionPolicy="LRU"/><cache name="USER_SESSION"maxElementsInMemory="500"eternal="false"timeToIdleSeconds="300"timeToLiveSeconds="600"/>
</ehcache>
<!--       name:緩存名稱。-->
<!--       maxElementsInMemory:緩存最大個數。-->
<!--       eternal:對象是否永久有效,一但設置了,timeout將不起作用。-->
<!--       timeToIdleSeconds:設置對象在失效前的允許閑置時間(單位:秒)。僅當eternal=false對象不是永久有效時使用,可選屬性,默認值是0,也就是可閑置時間無窮大。-->
<!--       timeToLiveSeconds:設置對象在失效前允許存活時間(單位:秒)。最大時間介于創建時間和失效時間之間。僅當eternal=false對象不是永久有效時使用,默認是0.,也就是對象存活時間無窮大。-->
<!--       overflowToDisk:當內存中對象數量達到maxElementsInMemory時,Ehcache將會對象寫到磁盤中。-->
<!--       diskSpoolBufferSizeMB:這個參數設置DiskStore(磁盤緩存)的緩存區大小。默認是30MB。每個Cache都應該有自己的一個緩沖區。-->
<!--       maxElementsOnDisk:硬盤最大緩存個數。-->
<!--       diskPersistent:是否緩存虛擬機重啟期數據 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.-->
<!--       diskExpiryThreadIntervalSeconds:磁盤失效線程運行時間間隔,默認是120秒。-->
<!--       memoryStoreEvictionPolicy:當達到maxElementsInMemory限制時,Ehcache將會根據指定的策略去清理內存。默認策略是LRU(最近最少使用)。你可以設置為FIFO(先進先出)或是LFU(較少使用)。-->
<!--       clearOnFlush:內存數量最大時是否清除。-->

?application.yml中配置EhCache

指定EhCache的XML配置文件路徑:

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

4、使用緩存注解

Spring提供了多個注解來簡化緩存的使用,最常用的是@Cacheable@CachePut@CacheEvict

@Cacheable?注解用于方法上,表示該方法的返回值會被緩存。如果緩存中存在值,則不會執行方法體;

@CachePut?注解用于更新緩存。無論緩存中是否存在值,都會執行方法體,并將返回值更新到緩存中;

@CacheEvict?注解用于清除緩存。?

  • value:指定緩存的名稱,與ehcache.xml中的name保持一致;

  • key:指定緩存的鍵,默認是方法的參數。參考格式:'方法名_' + #參數名

package com.service.cache;import com.domain.User;
import com.mapstruct.UserMapper;
import com.repository.UserRepository;
import com.web.dto.UserDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;import java.util.List;
import java.util.Optional;@Slf4j
@Service
@RequiredArgsConstructor
public class UserCacheService {private final UserRepository userRepository;private final UserMapper userMapper;@Cacheable(value = "USER_SESSION", key = "'getUserById_' + #id")public User getUserById(Integer id) {if (id == null)return new User();Optional<User> userOptional = userRepository.findById(id);return userOptional.isPresent()? userOptional.get() : new User();}@Cacheable(value = "USER_SESSION", key = "'getUsersByRoleId_' + #roleId")public List<UserDto> getUsersByRoleId(Integer roleId) {if (roleId == null){List<User> optionals = userRepository.findAllByIsDeleteIsFalseOrderByNameAsc();return userMapper.toDto(optionals);} else {List<User> optionals = userRepository.findAllByRoleIdAndIsDeleteIsFalse(roleId);return userMapper.toDto(optionals);}}@CachePut(value = "USER_SESSION", key = "#id")public String updateDataById(String id, String newData) {System.out.println("Updating data in database...");return newData;}@CacheEvict(value = "USER_SESSION", key = "#id")public void deleteDataById(String id) {System.out.println("Deleting data from database...");}}

5、最后啟動ehcache

使用@EnableCaching注解啟動緩存:

package com.start;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeIn;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeType;
import io.swagger.v3.oas.annotations.security.SecurityScheme;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.scheduling.annotation.EnableScheduling;@EnableCaching
@EnableScheduling
@SpringBootApplication
@EntityScan("com.domain")
@SecurityScheme(name = "token", scheme = "Bearer", type = SecuritySchemeType.HTTP, in = SecuritySchemeIn.QUERY)
public class StartDataApplication extends SpringBootServletInitializer {public static void main(String[] args) {SpringApplication.run(StartDataApplication.class, args);}@Overrideprotected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {return builder.sources(StartDataApplication.class);}
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/pingmian/75475.shtml
繁體地址,請注明出處:http://hk.pswp.cn/pingmian/75475.shtml
英文地址,請注明出處:http://en.pswp.cn/pingmian/75475.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

NVIDIA顯卡

NVIDIA顯卡作為全球GPU技術的標桿&#xff0c;其產品線覆蓋消費級、專業級、數據中心、移動計算等多個領域&#xff0c;技術迭代貫穿架構創新、AI加速、光線追蹤等核心方向。以下從技術演進、產品矩陣、核心技術、生態布局四個維度展開深度解析&#xff1a; 一、技術演進&…

【BUG】生產環境死鎖問題定位排查解決全過程

目錄 生產環境死鎖問題定位排查解決過程0. 表面現象1. 問題分析&#xff08;1&#xff09;數據庫連接池資源耗盡&#xff08;2&#xff09;數據庫鎖競爭(3) 代碼實現問題 2. 分析解決(0) 分析過程&#xff08;1&#xff09;優化數據庫連接池配置&#xff08;2&#xff09;優化數…

【計算機網絡應用層】

文章目錄 計算機網絡應用層詳解一、前言二、應用層的功能三、常見的應用層協議1. HTTP/HTTPS&#xff08;超文本傳輸協議&#xff09;2. DNS&#xff08;域名系統&#xff09;3. FTP&#xff08;文件傳輸協議&#xff09;4. SMTP/POP3/IMAP&#xff08;電子郵件協議&#xff09…

Linux 虛擬化方案

一、Linux 虛擬化技術分類 1. 全虛擬化 (Full Virtualization) 特點&#xff1a;Guest OS 無需修改&#xff0c;完全模擬硬件 代表技術&#xff1a; KVM (Kernel-based Virtual Machine)&#xff1a;主流方案&#xff0c;集成到 Linux 內核 QEMU&#xff1a;硬件模擬器&…

樹莓派 5 換清華源

首先備份原設置 cp /etc/apt/sources.list ~/sources.list.bak cp /etc/apt/sources.list.d/raspi.list ~/raspi.list.bak修改配置 /etc/apt/sources.list 文件替換內容如下&#xff08;原內容刪除&#xff09; deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm …

WGAN原理及實現(pytorch版)

WGAN原理及實現 一、WGAN原理1.1 原始GAN的缺陷1.2 Wasserstein距離的引入1.3 Kantorovich-Rubinstein對偶1.4 WGAN的優化目標1.4 數學推導步驟1.5 權重裁剪 vs 梯度懲罰1.6 優勢1.7 總結 二、WGAN實現2.1 導包2.2 數據加載和處理2.3 構建生成器2.4 構建判別器2.5 訓練和保存模…

Unity網絡開發基礎 (3) Socket入門 TCP同步連接 與 簡單封裝練習

本文章不作任何商業用途 僅作學習與交流 教程來自Unity唐老獅 關于練習題部分是我觀看教程之后自己實現 所以和老師寫法可能不太一樣 唐老師說掌握其基本思路即可,因為前端程序一般不需要去寫后端邏輯 1.認識Socket的重要API Socket是什么 Socket&#xff08;套接字&#xff0…

【linux】一文掌握 ssh和scp 指令的詳細用法(ssh和scp 備忘速查)

文章目錄 入門連接執行SCP配置位置SCP 選項配置示例ProxyJumpssh-copy-id SSH keygenssh-keygen產生鑰匙類型known_hosts密鑰格式 此快速參考備忘單提供了使用 SSH 的各種方法。 參考&#xff1a; OpenSSH 配置文件示例 (cyberciti.biz)ssh_config (linux.die.net) 入門 連…

真實筆試題

文章目錄 線程題樹的深度遍歷 線程題 實現一個類支持100個線程同時向一個銀行賬戶中存入一元錢.需通過同步機制消除競態條件,當所有線程執行完成后,賬戶余額必須精確等于100元 package com.itheima.thread;public class ShowMeBug {private double balance; // 賬戶余額priva…

2.2 路徑問題專題:LeetCode 63. 不同路徑 II

動態規劃解決LeetCode 63題&#xff1a;不同路徑 II&#xff08;含障礙物&#xff09; 1. 題目鏈接 LeetCode 63. 不同路徑 II 2. 題目描述 一個機器人位于 m x n 網格的左上角&#xff0c;每次只能向右或向下移動一步。網格中可能存在障礙物&#xff08;標記為 1&#xff…

2874. 有序三元組中的最大值 II

給你一個下標從 0 開始的整數數組 。nums 請你從所有滿足 的下標三元組 中&#xff0c;找出并返回下標三元組的最大值。 如果所有滿足條件的三元組的值都是負數&#xff0c;則返回 。i < j < k(i, j, k)0 下標三元組 的值等于 。(i, j, k)(nums[i] - nums[j]) * nums[k…

【論文筆記】Llama 3 技術報告

Llama 3中的頂級模型是一個擁有4050億參數的密集Transformer模型&#xff0c;并且它的上下文窗口長度可以達到128,000個tokens。這意味著它能夠處理非常長的文本&#xff0c;記住和理解更多的信息。Llama 3.1的論文長達92頁&#xff0c;詳細描述了模型的開發階段、優化策略、模…

JVM深入原理(一+二):JVM概述和JVM功能

目錄 1. JVM概述 1.1. Java程序結構 1.2. JVM作用 1.3. JVM規范和實現 2. JVM功能 2.1. 功能-編譯和運行 2.2. 功能-內存管理 2.3. 功能-即時編譯 1. JVM概述 1.1. Java程序結構 1.2. JVM作用 JVM全稱是Java Virtual Machine-Java虛擬機 JVM作用:本質上是一個運行在…

SQL Server Integration Services (SSIS) 服務無法啟動

問題現象&#xff1a; 安裝 SQL Server 2022 后&#xff0c;SQL Server Integration Services (SSIS) 服務無法啟動&#xff0c;日志報錯 “服務無法響應控制請求”&#xff08;錯誤代碼 1067&#xff09;或 “依賴服務不存在或已標記為刪除”。 快速診斷 檢查服務狀態與依賴項…

Spring Boot 定時任務的多種實現方式

&#x1f31f; 前言 歡迎來到我的技術小宇宙&#xff01;&#x1f30c; 這里不僅是我記錄技術點滴的后花園&#xff0c;也是我分享學習心得和項目經驗的樂園。&#x1f4da; 無論你是技術小白還是資深大牛&#xff0c;這里總有一些內容能觸動你的好奇心。&#x1f50d; &#x…

Java基礎之反射的基本使用

簡介 在運行狀態中&#xff0c;對于任意一個類&#xff0c;都能夠知道這個類的所有屬性和方法&#xff1b;對于任意一個對象&#xff0c;都能夠調用它的任意屬性和方法&#xff1b;這種動態獲取信息以及動態調用對象方法的功能稱為Java語言的反射機制。反射讓Java成為了一門動…

AI產品的上層建筑:提示詞工程、RAG與Agent

上節課我們拆解了 AI 產品的基礎設施建設&#xff0c;這節課我們聊聊上層建筑。這部分是產品經理日常工作的重頭戲&#xff0c;包含提示詞、RAG 和 Agent 構建。 用 AI 客服產品舉例&#xff0c;這三者的作用是這樣的&#xff1a; 提示詞能讓客服很有禮貌。比如它會說&#x…

藍橋杯刷題記錄【并查集001】(2024)

主要內容&#xff1a;并查集 并查集 并查集的題目感覺大部分都是模板題&#xff0c;上板子&#xff01;&#xff01; class UnionFind:def __init__(self, n):self.pa list(range(n))self.size [1]*n self.cnt ndef find(self, x):if self.pa[x] ! x:self.pa[x] self.fi…

海外SD-WAN專線網絡部署成本分析

作為支撐企業國際業務的重要基石&#xff0c;海外SD-WAN專線以其獨特的成本優勢和技術特性&#xff0c;正成為企業構建高效穩定的全球網絡架構的首選方案。本文將從多維度解構海外SD-WAN專線部署的核心成本要素&#xff0c;為企業的全球化網絡布局提供戰略參考。 一、基礎資源投…

操作系統(二):實時系統介紹與實例分析

目錄 一.概念 1.1 分類 1.2 主要指標 二.實現原理 三.主流實時系統對比 一.概念 實時系統&#xff08;Real-Time System, RTS&#xff09;是一類以時間確定性為核心目標的計算機系統&#xff0c;其設計需確保在嚴格的時間約束內完成任務響應。 1.1 分類 根據時間約束的嚴…