首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

MyBatis 整合 Ehcache 實現二級緩存:配置詳解與最佳實踐

     編輯:Java 相關知識

MyBatis 緩存機制速覽

  • 一級緩存:SqlSession 級別,默認開啟,同一會話內重複查詢命中
  • 二級緩存:Mapper 級別,跨會話共享,需顯式開啟

原生二級緩存配置

全局開關

<settings>
    <setting name="cacheEnabled" value="true"/>  <!-- 默認 true -->
</settings>

Mapper 級開啟

<mapper namespace="com.demo.mapper.UserMapper">
    <cache
        eviction="LRU"           <!-- 回收策略:LRU/FIFO/SOFT/WEAK -->
        flushInterval="60000"    <!-- 刷新間隔(ms),默認不自動刷新 -->
        size="1024"              <!-- 最大引用數 -->
        readOnly="false"         <!-- true: 直接返回實例(快但不安全) -->
    />
    <select id="selectUser" resultType="User">...</select>
</mapper>

整合 Ehcache:企業級緩存方案

依賴引入

<dependency>
    <groupId>org.mybatis.caches</groupId>
    <artifactId>mybatis-ehcache</artifactId>
    <version>1.2.1</version>
</dependency>

Mapper XML 指定緩存實現

<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
<!-- 帶日誌版:<cache type="org.mybatis.caches.ehcache.LoggingEhcache"/> -->

ehcache.xml 詳細配置(放在 classpath 根目錄)

<ehcache xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd"
         updateCheck="false">

    <defaultCache
        maxEntriesLocalHeap="10000"
        eternal="false"
        timeToIdleSeconds="300"
        timeToLiveSeconds="600"
        memoryStoreEvictionPolicy="LRU">
        <persistence strategy="none"/>
    </defaultCache>

    <!-- 針對特定命名空間定制 -->
    <cache name="com.demo.mapper.UserMapper"
           maxEntriesLocalHeap="5000"
           timeToLiveSeconds="1800"
           eternal="false">
    </cache>
</ehcache>

核心屬性對照

| 屬性 | 說明 | 推薦值 | |------|------|--------| | eternal | 永不過期,忽略 TTL/TTI | false | | timeToLiveSeconds | 生存時間 | 業務決定 (如 1800) | | timeToIdleSeconds | 閒置超時 | ≤ TTL | | memoryStoreEvictionPolicy | 內存回收策略 | LRU | | maxEntriesLocalHeap | 堆內最大條目 | 預估熱點數據量 |

進階技巧

  1. 緩存分片:不同 Mapper 使用不同 cache name,避免相互影響
  2. 只讀優化:readOnly="true" 返回同一實例,極大提升性能,但要求業務絕不修改返回對象
  3. 選擇性緩存:頻繁讀、極少寫的參考數據(字典、配置)適合緩存;交易數據慎用
  4. 緩存穿透/擊穿/雪崩:結合 Redis 多級緩存、互斥鎖、隨機過期時間解決

總結

MyBatis + Ehcache 只需在 Mapper XML 添加一行 <cache type="..."/>,即可獲得企業級緩存能力:持久化、分佈式擴展、豐富過期策略、JMX 監控。配合合理的 ehcache.xml,滿足絕多數業務場景。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved