SpringBoot系列:Spring Boot集成Spring Cache,使用EhCache

来源:https://www.cnblogs.com/imyanger/archive/2019/10/23/11729480.html
-Advertisement-
Play Games

前面的章節,講解了[Spring Boot集成Spring Cache]( https://blog.csdn.net/Simple_Yangger/article/details/102693316),Spring Cache已經完成了多種Cache的實現,包括EhCache、RedisCache ...


前面的章節,講解了Spring Boot集成Spring Cache,Spring Cache已經完成了多種Cache的實現,包括EhCache、RedisCache、ConcurrentMapCache等。

這一節我們來看看Spring Cache使用EhCache。

一、EhCache使用演示

EhCache是一個純Java的進程內緩存框架,具有快速、精幹等特點,Hibernate中的預設Cache就是使用的EhCache。

本章節示例是在Spring Boot集成Spring Cache的源碼基礎上進行改造。源碼地址:https://github.com/imyanger/springboot-project/tree/master/p20-springboot-cache

使用EhCache作為緩存,我們先引入相關依賴。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--ehcache依賴-->
<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

然後創建EhCache的配置文件ehcache.xml。

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
         updateCheck="false">

    <!--
        磁碟存儲:將緩存中暫時不使用的對象,轉移到硬碟,類似於Windows系統的虛擬記憶體
        path:指定在硬碟上存儲對象的路徑
        path可以配置的目錄有:
        user.home(用戶的家目錄)
        user.dir(用戶當前的工作目錄)
        java.io.tmpdir(預設的臨時目錄)
        ehcache.disk.store.dir(ehcache的配置目錄)
        絕對路徑(如:d:\\ehcache)
        查看路徑方法:String tmpDir = System.getProperty("java.io.tmpdir");
     -->
    <diskStore path="java.io.tmpdir" />

    <!--
        defaultCache:預設的緩存配置信息,如果不加特殊說明,則所有對象按照此配置項處理
        maxElementsInMemory:設置了緩存的上限,最多存儲多少個記錄對象
        eternal:代表對象是否永不過期 (指定true則下麵兩項配置需為0無限期)
        timeToIdleSeconds:最大的發呆時間 /秒
        timeToLiveSeconds:最大的存活時間 /秒
        overflowToDisk:是否允許對象被寫入到磁碟
        說明:下列配置自緩存建立起600秒(10分鐘)有效 。
        在有效的600秒(10分鐘)內,如果連續120秒(2分鐘)未訪問緩存,則緩存失效。
        就算有訪問,也只會存活600秒。
     -->
    <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="600"
                  timeToLiveSeconds="600" overflowToDisk="true" />

    <cache name="cache" maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120"
           timeToLiveSeconds="600" overflowToDisk="true" />

</ehcache>

然後SpringBoot配置文件中,指明緩存類型並聲明Ehcache配置文件的位置。

server:
  port: 10900

spring:
  profiles:
    active: dev
  cache:
    type: ehcache
    ehcache:
      config: classpath:/ehcache.xml

這樣就可以開始使用Ehcache了,測試代碼與Spring Boot集成Spring Cache一致。

SpringBoot啟動類,@EnableCaching開啟Spring Cache緩存功能。

@EnableCaching
@SpringBootApplication
public class SpringbootApplication {

    public static void main(String[] args) {
        String tmpDir = System.getProperty("java.io.tmpdir");
        System.out.println("臨時路徑:" + tmpDir);
        SpringApplication.run(SpringbootApplication.class, args);
    }

}

CacheApi介面調用類,方便調用進行測試。

@RestController
@RequestMapping("cache")
public class CacheApi {

    @Autowired
    private CacheService cacheService;

    @GetMapping("get")
    public User  get(@RequestParam int id){
        return cacheService.get(id);
    }

    @PostMapping("set")
    public User  set(@RequestParam int id, @RequestParam String code, @RequestParam String name){
        User u = new User(code, name);
        return cacheService.set(id, u);
    }

    @DeleteMapping("del")
    public void  del(@RequestParam int id){
        cacheService.del(id);
    }
    
}

CacheService緩存業務處理類,添加緩存,更新緩存和刪除。

@Slf4j
@Service
public class CacheService {

    private Map<Integer, User> dataMap = new HashMap <Integer, User>(){
        {
            for (int i = 1; i < 100 ; i++) {
                User u = new User("code" + i, "name" + i);
                put(i, u);
            }
        }
     };

    // 獲取數據
    @Cacheable(value = "cache", key = "'user:' + #id")
    public User get(int id){
        log.info("通過id{}查詢獲取", id);
        return dataMap.get(id);
    }

    // 更新數據
    @CachePut(value = "cache", key = "'user:' + #id")
    public User set(int id, User u){
        log.info("更新id{}數據", id);
        dataMap.put(id, u);
        return u;
     }

    //刪除數據
    @CacheEvict(value = "cache", key = "'user:' + #id")
    public void del(int id){
        log.info("刪除id{}數據", id);
        dataMap.remove(id);
    }
    
}

源碼地址:https://github.com/imyanger/springboot-project/tree/master/p22-springboot-cache-ehcache


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 本片文章是基於前一篇寫的,《Spring Boot 入門(六):集成 treetable 和 zTree 實現樹形圖》,本篇主要介紹了spring boot集成swagger2。關於swagger的介紹,自行谷歌。我這裡有在網上購買的相關視頻資料,有需要可以呼叫我。 1.引入相關依賴 很多地方只引入 ...
  • 恢復內容開始 恢復內容結束 ...
  • 深入理解Java記憶體模型 【1】CPU和緩存的一致性 ​ 我們應該都知道,電腦在執行程式的時候,每條指令都是在CPU中執行的,而執行的時候,又免不了要和數據打交道。而電腦上面的數據,是存放在主存當中的,也就是電腦的物理記憶體啦。 ​ 剛開始,還相安無事的,但是隨著CPU技術的發展,CPU的執行速 ...
  • 模塊在python編程中的地位舉足輕重,熟練運用模塊可以大大減少代碼量,以最少的代碼實現複雜的功能。 下麵介紹一下在python編程中如何導入模塊: (1)import 模塊名:直接導入,這裡導入模塊中的所有與函數; 這裡的模塊也可以是自己編寫的腳本名稱,如: (2) from 模塊名 import ...
  • 原文地址: "梁桂釗的博客" 博客地址: "http://blog.720ui.com" 歡迎關註公眾號:「服務端思維」。一群同頻者,一起成長,一起精進,打破認知的局限性。 今天,探討一個有趣的話題:我們可以通過 Git 來實現項目版本控制;通過 Jenkins 進行持續集成,那麼對於資料庫層面,我 ...
  • 集合類 Collection介面 定義的是所有單列集合中共性方法 創建對象使用多態 Collection<String> coll = new ArrayList<>() add() 把給定的對象添加到當前集合中,返回一個boolean值 remove() 在集合中刪除指定的對象,返回一個boole ...
  • 一、json數據 python數據類型與json對應關係表如下: 以上就是關於json的所有數據類型。 什麼是json? 定義: 講json對象,不得不提到JS對象: 合格的json對象: 不合格的json對象: python數據類型和json的轉換 JavaScript數據類型和json的轉換 p ...
  • 前面的章節,講解了[Spring Boot集成Spring Cache]( https://blog.csdn.net/Simple_Yangger/article/details/102693316),Spring Cache已經完成了多種Cache的實現,包括EhCache、RedisCache ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...