项目概况

第06篇:Mybatis缓存设计

2026-01-293 min read后端技术
Mybatis

官方文档

!!!tip MyBatis 内置了一个强大的事务性查询缓存机制,它可以非常方便地配置和定制。本篇文章,小编将会在最短的时间呢,通过观察源码来深刻了解Mybatis的 一级二级缓存;然后在说如何定制。 !!!

一、Mybatis Cache设计

在Mybatis中所有的缓存,都是实现自Cache接口。无论是一级缓存还是二级缓存都是实现这个接口。其中一级缓存是本地缓存,二级缓存是一个允许开发者扩展的 缓存(eg: ehcache/或者内置的很多缓存)。

java
1public interface Cache { 2 3 String getId(); 4 5 void putObject(Object key, Object value); 6 7 Object getObject(Object key); 8 9 Object removeObject(Object key); 10 11 void clear(); 12 13 int getSize(); 14 15 default ReadWriteLock getReadWriteLock() { 16 return null; 17 } 18 19} 20

二、一级缓存

一级缓存是本地缓存,其实就是PerpetualCache这类,它的源码也很简单,其实就是一个Map而已。一般面试的经常说一级缓存称为 SqlSession缓存,我们看其实最终实现是在BaseExecutor进行做的。就这么简单。

java
1public abstract class BaseExecutor implements Executor { 2 3 // 一级缓存本地缓存 4 protected PerpetualCache localCache; 5 6 protected BaseExecutor(Configuration configuration, Transaction transaction) { 7 this.transaction = transaction; 8 this.deferredLoads = new ConcurrentLinkedQueue<>(); 9 this.localCache = new PerpetualCache("LocalCache"); 10 } 11 12 // 执行查询后添加到一级缓存中 13 private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException { 14 List<E> list; 15 localCache.putObject(key, EXECUTION_PLACEHOLDER); 16 try { 17 list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql); 18 } finally { 19 localCache.removeObject(key); 20 } 21 localCache.putObject(key, list); 22 if (ms.getStatementType() == StatementType.CALLABLE) { 23 localOutputParameterCache.putObject(key, parameter); 24 } 25 return list; 26 } 27}

三、二级缓存

二级缓存是基于装饰器模式,它允许开发者自定义缓存的实现,只要实现了Cache接口就行。通过装饰器的设计。 CachingExecutor从MappedStatement#getCache获取缓存的具体实现,从而进行缓存操作。

下面代码是看Mybatis是如何进行装饰器的。注意看注释。如果开启缓存,则包装器对Executor进行包装。

java
1public class Configuration { 2 public Executor newExecutor(Transaction transaction, ExecutorType executorType) { 3 executorType = executorType == null ? defaultExecutorType : executorType; 4 executorType = executorType == null ? ExecutorType.SIMPLE : executorType; 5 Executor executor; 6 if (ExecutorType.BATCH == executorType) { 7 executor = new BatchExecutor(this, transaction); 8 } else if (ExecutorType.REUSE == executorType) { 9 executor = new ReuseExecutor(this, transaction); 10 } else { 11 executor = new SimpleExecutor(this, transaction); 12 } 13 // 如果开启缓存,则包装器对Executor进行包装 14 if (cacheEnabled) { 15 executor = new CachingExecutor(executor); 16 } 17 executor = (Executor) interceptorChain.pluginAll(executor); 18 return executor; 19 } 20}

CachingExecutor在实际执行时候从MappedStatement#getCache获取缓存的具体实现,从而进行缓存操作。 看到查询是先从二级缓存中获取,如果没有获取到就从一级缓存中获取,还没有就查询db。

java
1public class CachingExecutor implements Executor { 2 3 @Override 4 public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) 5 throws SQLException { 6 // 从MappedStatement获取Cache 7 Cache cache = ms.getCache(); 8 if (cache != null) { 9 flushCacheIfRequired(ms); 10 if (ms.isUseCache() && resultHandler == null) { 11 ensureNoOutParams(ms, boundSql); 12 @SuppressWarnings("unchecked") 13 List<E> list = (List<E>) tcm.getObject(cache, key); 14 if (list == null) { 15 list = delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql); 16 tcm.putObject(cache, key, list); // issue #578 and #116 17 } 18 return list; 19 } 20 } 21 return delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql); 22 } 23}

注意这里可以看到如果指定了要进行缓存,但是没有指定缓存的type默认是 PERPETUAL(PerpetualCache )

四、开启二级缓存

4.1 内置二级缓存

  1. 首先开启配置
  2. 同时在Mapper文件中添加标签 (XMLMapperBuilder#cacheElement)
  3. 或者是在Mapper类上添加@CacheNamespace注解(MapperAnnotationBuilder#parseCache)
xml
1<?xml version="1.0" encoding="UTF-8" ?> 2<!DOCTYPE configuration 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-config.dtd"> 5<configuration> 6 <!-- 指定Mybatis使用log4j --> 7 <settings> 8 <setting name="logImpl" value="LOG4J"/> 9 // 通过 cacheEnabled 进行配置,如果不配置默认是true 10 <setting name="cacheEnabled" value="false"/> 11 </settings> 12</configuration> 13 14<?xml version="1.0" encoding="UTF-8"?> 15<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 16<mapper namespace="orm.example.dal.mapper.TUserMapper"> 17 // 添加cache标签 18 <cache/> 19</mapper>
属性含义
eviction缓存回收策略
flushInterval缓存刷新间隔,缓存多长时间刷新一次,默认不清空,设置一个毫秒值
readOnly是否只读;true 只读
size缓存存放多少个元素
type指定自定义缓存的全类名(实现Cache 接口即可)
blocking若缓存中找不到对应的key,是否会一直blocking,直到有对应的数据进入缓存。

一共可以使用的二级缓存有以下这些。

4.2 外置二级缓存

只要实现了Cache接口那么Mybatis就会调用这个接口实现进行缓存。下面只说一个思路。如下通过指定EhcacheCache 就可以将这个二级缓存的能力,交给Mybatis进行调用了。

xml
1<cache type="org.mybatis.caches.ehcache.EhcacheCache" > 2 <property name="timeToIdleSeconds" value="3600"/> 3 <property name="timeToLiveSeconds" value="3600"/> 4 <!-- 同ehcache参数maxElementsInMemory --> 5 <property name="maxEntriesLocalHeap" value="1000"/> 6 <!-- 同ehcache参数maxElementsOnDisk --> 7 <property name="maxEntriesLocalDisk" value="10000000"/> 8 <property name="memoryStoreEvictionPolicy" value="LRU"/> 9</cache>