springboot-mybatis-plus 整合Ehcache開啟二級緩存


Ehcache是一種廣泛使用的開源Java分布式緩存。主要面向通用緩存,Java EE和輕量級容器。它具有內存和磁盤存儲,緩存加載器,緩存擴展,緩存異常處理程序,一個gzip緩存servlet過濾器,支持REST和SOAP api等特點。
Ehcache最初是由Greg Luck於2003年開始開發。2009年,該項目被Terracotta購買。軟件仍然是開源,但一些新的主要功能(例如,快速可重啟性之間的一致性的)只能在商業產品中使用,例如Enterprise EHCache and BigMemory。維基媒體Foundationannounced目前使用的就是Ehcache技術。
主要的特性有:
1. 快速
2. 簡單
3. 多種緩存策略
4. 緩存數據有兩級:內存和磁盤,因此無需擔心容量問題
5. 緩存數據會在 虛擬機重啟的過程中寫入磁盤
6. 可以通過RMI、可插入API等方式進行分布式緩存
7. 具有緩存和緩存管理器的偵聽接口
8. 支持多 緩存管理器實例,以及一個實例的多個緩存區域
9. 提供Hibernate的緩存實現
                                                    ----百度百科
 
1.新建一個springboot 項目 在我們的pom.xml 文件中添加如下配置
		<!-- mybatisPlus 核心庫 -->
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-boot-starter</artifactId>
			<version>3.1.0</version>
		</dependency>

		<dependency> <!-- 開啟二級緩存 -->
			<groupId>org.mybatis.caches</groupId>
			<artifactId>mybatis-ehcache</artifactId>
			<version>1.1.0</version>
		</dependency>

 

2. 在我們的配置文件中開啟mybatis的二級緩存 並配置ehcache.xml 文件路徑

mybatis-plus.configuration.cache-enabled=true
spring.cache.ehcache.config=classpath:/ehcache.xml

  

3.新建 ehcache.xml 文件  文件的路徑 src/main/resources/ehcache.xml 

  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">

<!-- 磁盤緩存位置
path屬性可以配置的目錄有:
    user.home(用戶的家目錄)
    user.dir(用戶當前的工作目錄)
    java.io.tmpdir(默認的臨時目錄)
    ehcache.disk.store.dir(ehcache的配置目錄)
    絕對路徑(如:d:\\ehcache)
-->
<diskStore path="java.io.tmpdir" />

<!--
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:內存數量最大時是否清除。
-->


<!-- 默認緩存 -->
<defaultCache
eternal="false"
maxElementsInMemory="1000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="0"
timeToLiveSeconds="600"
memoryStoreEvictionPolicy="LRU" />

<!-- 自定義緩存 -->
<cache
name="MyCache"
eternal="false"
maxElementsInMemory="1000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="5"
timeToLiveSeconds="5"
memoryStoreEvictionPolicy="LRU" />

</ehcache>

  

 4.在我們的mapper文件中 添加如下配置

  <cache type="org.mybatis.caches.ehcache.EhcacheCache">
    <property name="timeToIdleSeconds" value="3600"/>
    <property name="timeToLiveSeconds" value="3600"/>
    <property name="maxEntriesLocalHeap" value="1000"/>
    <property name="maxEntriesLocalDisk" value="10000000"/>
    <property name="memoryStoreEvictionPolicy" value="LRU"/>
  </cache>

  

 新建一個controller 測試   初次查詢訪問數據庫

 

  再次點擊查詢  可以看到並未訪問數據庫 結果依舊返回了

 

 

 現在測試當我更新數據后 是否會重新查詢數據庫  執行修改方法

 

 

修改數據庫 再次點擊查詢  並未走緩存 而是直接去查詢數據庫 

在這里有個問題  我使用的更新方法是我自己寫的mapper 在xml文件中有sql,mybatis-plus 自己生成的一系列方法 並未進入緩存

如有解決方案請 聯系我

新建測試方法來打印cache緩存的數據 在網上查詢到有 ehcache-monitor 管理工具 但是我並未找到對應的文件

這面我還是用代碼來打印數據

      CacheManager manager = CacheManager.create(this.getClass().getClassLoader().getResourceAsStream("classpath:ehcache.xml"));
        DateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String[] cacheNames = manager.getCacheNames();
        System.out.println("讀取的緩存列表為:");
        for (int i = 0; i < cacheNames.length; i++) {
            Cache cache = manager.getCache(cacheNames[i]);
            System.out.println("--" + (i + 1) + " " + cacheNames[i]);
            //緩存元素集合
            System.out.println("-----------------------緩存元素統計數據---------------------------------");
            List keys = cache.getKeys();
            for (Object key : keys) {
                Element ele = cache.get(key);
                System.out.println("內容: " + ele.getValue());
                System.out.println("創建時間: " + sf.format(ele.getCreationTime()));
                System.out.println("最后訪問時間: " + sf.format(ele.getLastAccessTime()));
                System.out.println("過期時間: " + sf.format(ele.getExpirationTime()));
                System.out.println("最后更新時間: " + sf.format(ele.getLastUpdateTime()));
                System.out.println("命中次數: " + ele.getHitCount());
                System.out.println("存活時間: " + ele.getTimeToLive() + "ms");
                System.out.println("空閑時間: " + ele.getTimeToIdle() + "ms");
            }
            System.out.println("--------------------------------------------------------");

            System.out.println("-----------------------緩存總統計數據---------------------------------");
            long elementsInMemory1 = cache.getMemoryStoreSize();
            System.out.println("得到緩存對象占用內存的數量:" + elementsInMemory1);

            long elementsInMemory2 = cache.getDiskStoreSize();
            System.out.println("得到緩存對對象占用磁盤的數量:" + elementsInMemory2);

            //獲取緩存統計對象
            Statistics stat = cache.getStatistics();
            long hits = stat.getCacheHits();
            System.out.println("得到緩存讀取的命中次數:" + hits);

            long memoryHits = stat.getInMemoryHits();
            System.out.println("得到內存中緩存讀取的命中次數:" + memoryHits);

            long diskHits = stat.getOnDiskHits();
            System.out.println("得到磁盤中緩存讀取的命中次數:" + diskHits);

            long cacheMisses = stat.getCacheMisses();
            System.out.println("得到緩存讀取的丟失次數:" + cacheMisses);

            long evictionCount = stat.getEvictionCount();
            System.out.println("得到緩存讀取的已經被銷毀的對象丟失次數:" + evictionCount);

            System.out.println("--------------------------------------------------------");
        }

  

控制台的輸出為

讀取的緩存列表為:
--1 MyCache
-----------------------緩存元素統計數據---------------------------------
--------------------------------------------------------
-----------------------緩存總統計數據---------------------------------
得到緩存對象占用內存的數量:0
得到緩存對對象占用磁盤的數量:0
得到緩存讀取的命中次數:0
得到內存中緩存讀取的命中次數:0
得到磁盤中緩存讀取的命中次數:0
得到緩存讀取的丟失次數:0
得到緩存讀取的已經被銷毀的對象丟失次數:0
--------------------------------------------------------
--2 com.demonlover.wx.auth.mapper.ContentMapper
-----------------------緩存元素統計數據---------------------------------
內容: [Content(id=28, categoryId=89, title=標題, subTitle=子標題, titleDesc=標題說明, url=http://www.jd.com, pic=, pic2=, content=, created=Sun Apr 07 13:56:09 CST 2019, updated=Sun Apr 07 13:56:11 CST 2019)]
創建時間: 2020-06-24 16:04:55
最后訪問時間: 2020-06-24 16:04:57
過期時間: 2020-06-24 17:04:55
最后更新時間: 2020-06-24 16:04:55
命中次數: 1
存活時間: 3600ms
空閑時間: 3600ms
--------------------------------------------------------
-----------------------緩存總統計數據---------------------------------
得到緩存對象占用內存的數量:1
得到緩存對對象占用磁盤的數量:0
得到緩存讀取的命中次數:0
得到內存中緩存讀取的命中次數:0
得到磁盤中緩存讀取的命中次數:0
得到緩存讀取的丟失次數:0
得到緩存讀取的已經被銷毀的對象丟失次數:0
--------------------------------------------------------

 

 

 

 

 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM