<settings>
<setting name="cacheEnabled" value="true"/> <!-- 默認 true -->
</settings>
<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>
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.2.1</version>
</dependency>
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/> <!-- 帶日誌版:<cache type="org.mybatis.caches.ehcache.LoggingEhcache"/> -->
<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 | 堆內最大條目 | 預估熱點數據量 |
readOnly="true" 返回同一實例,極大提升性能,但要求業務絕不修改返回對象MyBatis + Ehcache 只需在 Mapper XML 添加一行 <cache type="..."/>,即可獲得企業級緩存能力:持久化、分佈式擴展、豐富過期策略、JMX 監控。配合合理的 ehcache.xml,滿足絕多數業務場景。