一、二级缓存源码基本剖析


二级缓存构建在一级缓存之上,在收到查询请求时,MyBatis 首先会查询二级缓存,若二级缓存未命中,再去查询一级缓存,一级缓存没有,再查询数据库。

二级缓存———》 一级缓存 》数据库
与一级缓存不同,二级缓存和具体的命名空间绑定,一个Mapper中有一个Cache,相同Mapper中的
MappedStatement共用一个Cache,一级缓存则是和 SqlSession 绑定。

1 启用二级缓存

分为三步走:

  1. 开启全局二级缓存配置:

    1. <settings>
    2. <setting name="cacheEnabled" value="true"/>
    3. </settings>
  2. 在需要使用二级缓存的Mapper配置文件中配置标签

    <cache></cache>
    
  3. 在具体CURD标签上配置 useCache=true(默认为true)

    <select id="findById" resultType="com.lagou.pojo.User" useCache="true">
     select * from user where id = #{id}
    </select>
    

    2 标签 < cache/> 的解析

    2.1 cache标签解析


    根据之前的mybatis源码剖析,xml的解析工作主要交给XMLConfigBuilder.parse()方法来实现 ```java // XMLConfigBuilder.parse() public Configuration parse() { if (parsed) {

     throw new BuilderException("Each XMLConfigBuilder can only be used once.");
    

    } parsed = true; parseConfiguration(parser.evalNode(“/configuration”));// 在这里 return configuration; }

// parseConfiguration() // 既然是在xml中添加的,那么我们就直接看关于mappers标签的解析 private void parseConfiguration(XNode root) { try { // 省略了部分代码 // 就是这里 mapperElement(root.evalNode(“mappers”)); } catch (Exception e) { throw new BuilderException(“Error parsing SQL Mapper Configuration.Cause: “ + e, e); } }

// mapperElement() private void mapperElement(XNode parent) throws Exception { if (parent != null) { for (XNode child : parent.getChildren()) { if (“package”.equals(child.getName())) { String mapperPackage = child.getStringAttribute(“name”); configuration.addMappers(mapperPackage); } else { String resource = child.getStringAttribute(“resource”); String url = child.getStringAttribute(“url”); String mapperClass = child.getStringAttribute(“class”); // 按照我们本例的配置,则直接走该if判断 if (resource != null && url == null && mapperClass == null) { ErrorContext.instance().resource(resource); InputStream inputStream = Resources.getResourceAsStream(resource); XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments()); // 生成XMLMapperBuilder,并执行其parse方法【这里】 mapperParser.parse(); } else if (resource == null && url != null && mapperClass == null) { ErrorContext.instance().resource(url); InputStream inputStream = Resources.getUrlAsStream(url); XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments()); mapperParser.parse(); } else if (resource == null && url == null && mapperClass != null) { Class<?> mapperInterface = Resources.classForName(mapperClass); configuration.addMapper(mapperInterface); } else { throw new BuilderException(“A mapper element may only specify a url, resource or class, but not more than one.”);

            }
        }
    }
}

}

我们来看看解析Mapper.xml
```java
// XMLMapperBuilder.parse() 
public void parse() {
    if (!configuration.isResourceLoaded(resource)) {
        // 解析mapper属性
        configurationElement(parser.evalNode("/mapper")); 
        configuration.addLoadedResource(resource); bindMapperForNamespace();
    }

    parsePendingResultMaps(); 
    parsePendingChacheRefs(); 
    parsePendingStatements();
}

// configurationElement()
private void configurationElement(XNode context) { 
    try {
        String namespace = context.getStringAttribute("namespace"); 
        if (namespace == null || namespace.equals("")) {
            throw new BuilderException("Mapper's namespace cannot be empty");
        }
        builderAssistant.setCurrentNamespace(namespace); 
        // 用于引入其他标签
        cacheRefElement(context.evalNode("cache-ref"));

        // 最终在这里看到了关于cache属性的处理
        cacheElement(context.evalNode("cache")); 
        parameterMapElement(context.evalNodes("/mapper/parameterMap")); 
        resultMapElements(context.evalNodes("/mapper/resultMap")); 
        sqlElement(context.evalNodes("/mapper/sql"));


        //  这里会将生成的Cache包装到对应的MappedStatement
        buildStatementFromContext(context.evalNodes("select|insert|update|delete"));
    } catch (Exception e) {
        throw new BuilderException("Error parsing Mapper XML. Cause: " + e, e);
    }
}

// 解析 <cache /> 标签
private void cacheElement(XNode context) throws Exception {
    if (context != null) {
        // 解析<cache/>标签的type属性,这里我们可以自定义cache的实现类,比如redisCache,
        // 如果没有自定义,这里使用和一级缓存相同的PERPETUAL
        String type = context.getStringAttribute("type", "PERPETUAL");
        Class<? extends Cache> typeClass = typeAliasRegistry.resolveAlias(type);
        // 获得负责过期的 Cache 实现类
        String eviction = context.getStringAttribute("eviction", "LRU");
        Class<? extends Cache> evictionClass = typeAliasRegistry.resolveAlias(eviction);
        // 清空缓存的频率。0 代表不清空
        Long flushInterval = context.getLongAttribute("flushInterval");
        // 缓存容器大小
        Integer size = context.getIntAttribute("size");
        // 是否序列化
        boolean readWrite = !context.getBooleanAttribute("readOnly", false);
        // 是否阻塞
        boolean blocking = context.getBooleanAttribute("blocking", false);
        // 获得 Properties 属性
        Properties props = context.getChildrenAsProperties();
        // 创建 Cache 对象
        builderAssistant.useNewCache(typeClass, evictionClass, flushInterval, 
                                     size, readWrite, blocking, props);
    }
}

2.2 Cache对象的创建

先来看看是如何构建Cache对象的
MapperBuilderAssistant.useNewCache()

public Cache useNewCache(Class<? extends Cache> typeClass,
                             Class<? extends Cache> evictionClass,
                             Long flushInterval,
                             Integer size,
                             boolean readWrite,
                             boolean blocking,
                             Properties props) {

        // 1.生成Cache对象
        Cache cache = new CacheBuilder(currentNamespace)
                //这里如果我们定义了<cache/>中的type,就使用自定义的Cache,否则使用和一级缓存相同的PerpetualCache
                .implementation(valueOrDefault(typeClass, PerpetualCache.class))
                .addDecorator(valueOrDefault(evictionClass, LruCache.class))
                .clearInterval(flushInterval)
                .size(size)
                .readWrite(readWrite)
                .blocking(blocking)
                .properties(props)
                .build();
        // 2.添加到Configuration中
        configuration.addCache(cache);
        // 3.并将cache赋值给MapperBuilderAssistant.currentCache
        currentCache = cache;
        return cache;
    }

我们看到一个Mapper.xml只会解析一次标签,也就是只创建一次Cache对象,放进configuration中,并将cache赋值给MapperBuilderAssistant.currentCache

2.3 Cache包装到MappedStatement

org.apache.ibatis.builder.xml.XMLMapperBuilder#configurationElement,省略了部分代码

// configurationElement()
private void configurationElement(XNode context) { 
    try {
        String namespace = context.getStringAttribute("namespace"); 

        // 最终在这里看到了关于cache属性的处理
        cacheElement(context.evalNode("cache")); 

        //  这里会将生成的Cache包装到对应的MappedStatement
        buildStatementFromContext(context.evalNodes("select|insert|update|delete"));
    } catch (Exception e) {
        throw new BuilderException("Error parsing Mapper XML. Cause: " + e, e);
    }
}

buildStatementFromContext(context.evalNodes(“select|insert|update|delete”));
// 将Cache包装到MappedStatement

// 解析 <select /> <insert /> <update /> <delete /> 节点们
private void buildStatementFromContext(List<XNode> list) {
    if (configuration.getDatabaseId() != null) {
        buildStatementFromContext(list, configuration.getDatabaseId());
    }
    buildStatementFromContext(list, null);
    // 上面两块代码,可以简写成 buildStatementFromContext(list, configuration.getDatabaseId());
}

private void buildStatementFromContext(List<XNode> list, String requiredDatabaseId) {
    //遍历 <select /> <insert /> <update /> <delete /> 节点们
    for (XNode context : list) {
        // 创建 XMLStatementBuilder 对象,执行解析
        final XMLStatementBuilder statementParser = new XMLStatementBuilder(configuration, builderAssistant, context, requiredDatabaseId);
        try {

            // 每一条执行语句转换成一个MappedStatement 【这里】
            statementParser.parseStatementNode();
        } catch (IncompleteElementException e) {
            // 解析失败,添加到 configuration 中
            configuration.addIncompleteStatement(statementParser);
        }
    }
}

 /**
   * 执行解析
   */
public void parseStatementNode() {
    // 获得 id 属性,编号。
    String id = context.getStringAttribute("id");
    // 获得 databaseId , 判断 databaseId 是否匹配
    String databaseId = context.getStringAttribute("databaseId");
    if (!databaseIdMatchesCurrent(id, databaseId, this.requiredDatabaseId)) {
        return;
    }

    // 获得各种属性
    Integer fetchSize = context.getIntAttribute("fetchSize");
    Integer timeout = context.getIntAttribute("timeout");
    String parameterMap = context.getStringAttribute("parameterMap");
    String parameterType = context.getStringAttribute("parameterType");
    Class<?> parameterTypeClass = resolveClass(parameterType);
    String resultMap = context.getStringAttribute("resultMap");
    String resultType = context.getStringAttribute("resultType");
    String lang = context.getStringAttribute("lang");

    // 获得 lang 对应的 LanguageDriver 对象
    LanguageDriver langDriver = getLanguageDriver(lang);

    //…………
    // 获得各种属性
    boolean isSelect = sqlCommandType == SqlCommandType.SEL
    boolean flushCache = context.getBooleanAttribute("flushCache", !isSelect);
    boolean useCache = context.getBooleanAttribute("useCache", isSelect);

    // 创建 MappedStatement 对象
    builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType,
      fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass,
      resultSetTypeEnum, flushCache, useCache, resultOrdered,
      keyGenerator, keyProperty, keyColumn, databaseId, langDriver, resultSets);
}


 // 构建 MappedStatement 对象:
 // org.apache.ibatis.builder.MapperBuilderAssistant#addMappedStatement
public MappedStatement addMappedStatement(
    String id,
    SqlSource sqlSource,
    StatementType statementType,
    …………
    SqlCommandType sqlCommandType,
    String resultSets) {

    // 如果只想的 Cache 未解析,抛出 IncompleteElementException 异常
    if (unresolvedCacheRef) {
        throw new IncompleteElementException("Cache-ref not yet resolved");
    }

    // 获得 id 编号,格式为 `${namespace}.${id}`
    id = applyCurrentNamespace(id, false);
    boolean isSelect = sqlCommandType == SqlCommandType.SELECT;

    // 创建 MappedStatement.Builder 对象
    MappedStatement.Builder statementBuilder = 
        new MappedStatement.Builder(configuration, id, sqlSource, sqlCommandType)
        .resource(resource)
        .fetchSize(fetchSize)
        …………
        .resultMaps(getStatementResultMaps(resultMap, resultType, id)) 
        // 获得 ResultMap 集合
        .resultSetType(resultSetType)
        .flushCacheRequired(valueOrDefault(flushCache, !isSelect))
        .useCache(valueOrDefault(useCache, isSelect))
        .cache(currentCache); // 在这里将之前生成的Cache封装到MappedStatement【重点】

    // 获得 ParameterMap ,并设置到 MappedStatement.Builder 中
    ParameterMap statementParameterMap = 
        getStatementParameterMap(parameterMap, parameterType, id);
    if (statementParameterMap != null) {
        statementBuilder.parameterMap(statementParameterMap);
    }

    // 创建 MappedStatement 对象
    MappedStatement statement = statementBuilder.build();
    // 添加到 configuration 中
    configuration.addMappedStatement(statement);
    return statement;
}

我们看到将Mapper中创建的Cache对象,加入到了每个MappedStatement对象中,也就是同一个
Mapper中所有的2
有关于标签的解析就到这了。

3 查询源码分析

3.1 CachingExecutor

    @Override
    public <E> List<E> selectList(String statement, Object parameter, 
                                  RowBounds rowBounds) {
        try {
            // 获得 MappedStatement 对象
            MappedStatement ms = configuration.getMappedStatement(statement);
            // 执行查询
            return executor.query(ms, wrapCollection(parameter), rowBounds, 
                                  Executor.NO_RESULT_HANDLER);
        } catch (Exception e) {
            throw ExceptionFactory.wrapException("Error querying database.  Cause: " + e, e);
        } finally {
            ErrorContext.instance().reset();
        }
    }

executor#query方法,这里是调用的CachingExecutor实现类中的方法,因为开启了二级缓存。

// CachingExecutor
public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, 
                   ResultHandler resultHandler) throws SQLException {
    BoundSql boundSql = ms.getBoundSql(parameterObject);
    // 创建 CacheKey
    CacheKey key = createCacheKey(ms, parameterObject, rowBounds, boundSql); 
    return query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
}

public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds,
                         ResultHandler resultHandler, CacheKey key, BoundSql boundSql) 
    throws SQLException {
    // 从 MappedStatement 中获取 Cache,注意这里的 Cache 是从MappedStatement中获取的
    // 也就是我们上面解析Mapper中标签<cache/>中创建的,它保存在Configration中
    // 我们在上面解析blog.xml时分析过每一个MappedStatement都有一个Cache对象,就是这里
    Cache cache = ms.getCache();

    // 如果配置文件中没有配置<cache/>,则 cache 为空
    if (cache != null) {
        //如果需要刷新缓存的话就刷新:flushCache="true" 
        flushCacheIfRequired(ms);
        if (ms.isUseCache() && resultHandler == null) { 
            ensureNoOutParams(ms, boundSql);
            // 访问二级缓存
            List list = (List) tcm.getObject(cache, key);
            // 缓存未命中
            if (list == null) {
                // delegate:被委托的 Executor 对象,SimpleExecutor
                // 如果没有值,则执行查询,这个查询实际也是先走一级缓存查询,
                // 一级缓存也没有的话,则进行DB查询
                list = delegate.query(ms, parameterObject, rowBounds, 
                                      resultHandler, key, boundSql);
                // 缓存查询结果
                tcm.putObject(cache, key, list);
            }
            return list;
        }
    }
    return delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
}

如果设置了flushCache=”true”,则每次查询都会刷新缓存

<!-- 执行此语句清空缓存 -->
<select id="findbyId" resultType="com.lagou.pojo.user" useCache="true" flushCache="true" >
    select * from t_demo
</select>

如上,注意二级缓存是从 MappedStatement 中获取的。由于 MappedStatement 存在于全局配置中, 可以多个 CachingExecutor 获取到,这样就会出现线程安全问题。除此之外,若不加以控制,多个事务共用一个缓存实例,会导致脏读问题。至于脏读问题,需要借助其他类来处理,也就是上面代码中 tcm 变量对应的类型。下面分析一下。

3.2 TransactionalCacheManager

org.apache.ibatis.cache.TransactionalCacheManager :事务缓存管理器

/** 事务缓存管理器 */
public class TransactionalCacheManager {

    // Cache 与 TransactionalCache 的映射关系表
    private final Map<Cache, TransactionalCache> transactionalCaches = new HashMap<Cache, TransactionalCache>();

    public void clear(Cache cache) {
        // 获取 TransactionalCache 对象,并调用该对象的 clear 方法,下同
        getTransactionalCache(cache).clear();
    }

    public Object getObject(Cache cache, CacheKey key) {
        // 直接从TransactionalCache中获取缓存
        return getTransactionalCache(cache).getObject(key);
    }

    public void putObject(Cache cache, CacheKey key, Object value) {
        // 直接存入TransactionalCache的缓存中
        getTransactionalCache(cache).putObject(key, value);
    }

    public void commit() {
        for (TransactionalCache txCache : transactionalCaches.values()) {
            txCache.commit();
        }
    }

    public void rollback() {
        for (TransactionalCache txCache : transactionalCaches.values()) {
            txCache.rollback();
        }
    }

    private TransactionalCache getTransactionalCache(Cache cache) {
        // 从映射表中获取 TransactionalCache
        TransactionalCache txCache = transactionalCaches.get(cache);
        if (txCache == null) {
            // TransactionalCache 也是一种装饰类,为 Cache 增加事务功能
            // 创建一个新的TransactionalCache,并将真正的Cache对象存进去
            txCache = new TransactionalCache(cache);
            transactionalCaches.put(cache, txCache);
        }
        return txCache;
    }
}

TransactionalCacheManager 内部维护了 Cache 实例与 TransactionalCache 实例间的映射关系,该类也仅负责维护两者的映射关系,真正做事的还是 TransactionalCache。TransactionalCache 是一种缓存装饰器,可以为 Cache 实例增加事务功能。我在之前提到的脏读问题正是由该类进行处理的。下面分析一下该类的逻辑。

3.3 TransactionalCache

public class TransactionalCache implements Cache {
    // 真正的缓存对象,和上面的Map<Cache, TransactionalCache>中的Cache是同一个
    private final Cache delegate;
    private boolean clearOnCommit;
    // 在事务被提交前,所有从数据库中查询的结果将缓存在此集合中
    private final Map<Object, Object> entriesToAddOnCommit;
    // 在事务被提交前,当缓存未命中时,CacheKey 将会被存储在此集合中
    private final Set<Object> entriesMissedInCache;

    @Override
    public Object getObject(Object key) {
        // 查询的时候是直接从delegate中去查询的,也就是从真正的缓存对象中查询
        Object object = delegate.getObject(key);
        // 如果不存在,则添加到 entriesMissedInCache 中
        if (object == null) {
            // 缓存未命中,则将 key 存入到 entriesMissedInCache 中
            entriesMissedInCache.add(key);
        }
        // issue #146
        // 如果 clearOnCommit 为 true ,表示处于持续清空状态,则返回 null
        if (clearOnCommit) {
            return null;
        // 返回 value
        } else {
            return object;
        }
    }

    @Override
    public void putObject(Object key, Object object) {
        // 将键值对存入到 entriesToAddOnCommit 这个Map中,而非真实的缓存对象 delegate 中
        entriesToAddOnCommit.put(key, object);
    }

    @Override
    public Object removeObject(Object key) {
        return null;
    }

    @Override
    public void clear() {
        // 标记 clearOnCommit 为 true
        clearOnCommit = true;
        // 清空 entriesToAddOnCommit
        entriesToAddOnCommit.clear();
    }

    public void commit() {
        // 如果 clearOnCommit 为 true ,则清空 delegate 缓存
        if (clearOnCommit) {
            delegate.clear();
        }
        // 将 entriesToAddOnCommit、entriesMissedInCache 刷入 delegate(cache) 中
        flushPendingEntries();
        // 重置
        reset();
    }

    public void rollback() {
        // 从 delegate 移除出 entriesMissedInCache
        unlockMissedEntries();
        // 重置
        reset();
    }

    private void reset() {
        // 重置 clearOnCommit 为 false
        clearOnCommit = false;
        // 清空 entriesToAddOnCommit、entriesMissedInCache
        entriesToAddOnCommit.clear();
        entriesMissedInCache.clear();
    }

    /**
     * 将 entriesToAddOnCommit、entriesMissedInCache 刷入 delegate 中
     */
    private void flushPendingEntries() {
        // 将 entriesToAddOnCommit 中的内容转存到 delegate 中
        for (Map.Entry<Object, Object> entry : entriesToAddOnCommit.entrySet()) {

            // 在这里真正的将entriesToAddOnCommit的对象逐个添加到delegate中,只有这时,二级缓存才真正的生效
            delegate.putObject(entry.getKey(), entry.getValue());
        }
        // 将 entriesMissedInCache 刷入 delegate 中
        for (Object entry : entriesMissedInCache) {
            if (!entriesToAddOnCommit.containsKey(entry)) {
                delegate.putObject(entry, null);
            }
        }
    }

    private void unlockMissedEntries() {
        for (Object entry : entriesMissedInCache) {
            try {
                // 调用 removeObject 进行解锁
                delegate.removeObject(entry);
            } catch (Exception e) {
                log.warn("Unexpected exception while notifiying a rollback to the cache adapter."
                        + "Consider upgrading your cache adapter to the latest version.  Cause: " + e);
            }
        }
    }

}

存储二级缓存对象的时候是放到了TransactionalCache.entriesToAddOnCommit这个map中,但是每次查询的时候是直接从TransactionalCache.delegate中去查询的,所以这个二级缓存查询数据库后,设置缓存值是没有立刻生效的,主要是因为直接存到 delegate 会导致脏数据问题。

执行commit后会将entriesToAddOnCommit中的数据同步到delegate,避免读取到事务未结束的数据,即脏数据。

4 二级缓存的生效机制

那我们来看下SqlSession.commit()方法做了什么

@Override  
public void commit(boolean force) { 
    try {
        // 主要是这句
        executor.commit(isCommitOrRollbackRequired(force)); dirty = false;
    } catch (Exception e) {
        throw ExceptionFactory.wrapException("Error committing transaction.Cause: " + e, e);
    } finally {
        ErrorContext.instance().reset();
    }
}

// CachingExecutor.commit() 
@Override  
public void commit(boolean required) throws SQLException { 
    delegate.commit(required);
    tcm.commit();// 在这里
}

// TransactionalCacheManager.commit() 
public void commit() {
    for (TransactionalCache txCache : transactionalCaches.values()) { 
        txCache.commit();// 在这里
    }
}

// TransactionalCache.commit() 
public void commit() {
    if (clearOnCommit) { 
        delegate.clear();
    }
    flushPendingEntries();//这一句reset();
}

// TransactionalCache.flushPendingEntries() 
private void flushPendingEntries() {
    for (Map.Entry<Object, Object> entry : entriesToAddOnCommit.entrySet()) {
        // 在这里真正的将entriesToAddOnCommit的对象逐个添加到delegate中,只有这时,
        // 二级缓存才真正的生效
        delegate.putObject(entry.getKey(), entry.getValue());
    }
    for (Object entry : entriesMissedInCache) {
        if (!entriesToAddOnCommit.containsKey(entry)) {
            delegate.putObject(entry, null);
        }
    }
}

5 二级缓存的刷新

我们来看看SqlSession的更新操作

// org.apache.ibatis.session.defaults.DefaultSqlSession#update
public int update(String statement, Object parameter) {
    try {
        // 标记 dirty ,表示执行过写操作
        dirty = true;
        // 获得 MappedStatement 对象
        MappedStatement ms = configuration.getMappedStatement(statement);
        // 执行更新操作
        return executor.update(ms, wrapCollection(parameter));
    } catch (Exception e) {
        throw ExceptionFactory.wrapException("Error updating database.  Cause: " + e, e);
    } finally {
        ErrorContext.instance().reset();
    }
}
// org.apache.ibatis.executor.CachingExecutor#update
public int update(MappedStatement ms, Object parameterObject) throws SQLException {
    this.flushCacheIfRequired(ms);
    return this.delegate.update(ms, parameterObject);
}
// org.apache.ibatis.executor.CachingExecutor#flushCacheIfRequired
private void flushCacheIfRequired(MappedStatement ms) {
    //获取MappedStatement对应的Cache,进行清空
    Cache cache = ms.getCache();
    //SQL需设置flushCache="true" 才会执行清空
    if (cache != null && ms.isFlushCacheRequired()) { 
        this.tcm.clear(cache);
    }
}

MyBatis二级缓存只适用于不常进行增、删、改的数据,比如国家行政区省市区街道数据。一但数据变更,MyBatis会清空缓存。因此二级缓存不适用于经常进行更新的数据。

6 总结:

在二级缓存的设计上,MyBatis大量地运用了装饰者模式,如CachingExecutor, 以及各种Cache接口的装饰器。

  • 二级缓存实现了Sqlsession之间的缓存数据共享,属于namespace级别
  • 二级缓存具有丰富的缓存策略。
  • 二级缓存可由多个装饰器,与基础缓存组合而成
  • 二级缓存工作由 一个缓存装饰执行器CachingExecutor和 一个事务型预缓存TransactionalCache 完成。