MyBatis快取原始碼分析

丶Format的部落格發表於2014-12-13

MyBatis快取介紹

首先看一段wiki上關於MyBatis快取的介紹:

MyBatis支援宣告式資料快取(declarative data caching)。當一條SQL語句被標記為“可快取”後,首次執行它時從資料庫獲取的所有資料會被儲存在一段快取記憶體中,今後執行這條語句時就會從快取記憶體中讀取結果,而不是再次命中資料庫。MyBatis提供了預設下基於Java HashMap的快取實現,以及用於與OSCache、Ehcache、Hazelcast和Memcached連線的預設聯結器。MyBatis還提供API供其他快取實現使用。

重點的那句話就是:MyBatis執行SQL語句之後,這條語句就是被快取,以後再執行這條語句的時候,會直接從快取中拿結果,而不是再次執行SQL

這也就是大家常說的MyBatis一級快取,一級快取的作用域scope是SqlSession。

MyBatis同時還提供了一種全域性作用域global scope的快取,這也叫做二級快取,也稱作全域性快取。

一級快取

測試

同個session進行兩次相同查詢:

@Test
public void test() {
    SqlSession sqlSession = sqlSessionFactory.openSession();
    try {
        User user = (User)sqlSession.selectOne("org.format.mybatis.cache.UserMapper.getById", 1);
        log.debug(user);
        User user2 = (User)sqlSession.selectOne("org.format.mybatis.cache.UserMapper.getById", 1);
        log.debug(user2);
    } finally {
        sqlSession.close();
    }
}

MyBatis只進行1次資料庫查詢:

==>  Preparing: select * from USERS WHERE ID = ? 
==> Parameters: 1(Integer)
<==      Total: 1
User{id=1, name='format', age=23, birthday=Sun Oct 12 23:20:13 CST 2014}
User{id=1, name='format', age=23, birthday=Sun Oct 12 23:20:13 CST 2014}

同個session進行兩次不同的查詢:

@Test
public void test() {
    SqlSession sqlSession = sqlSessionFactory.openSession();
    try {
        User user = (User)sqlSession.selectOne("org.format.mybatis.cache.UserMapper.getById", 1);
        log.debug(user);
        User user2 = (User)sqlSession.selectOne("org.format.mybatis.cache.UserMapper.getById", 2);
        log.debug(user2);
    } finally {
        sqlSession.close();
    }
}

MyBatis進行兩次資料庫查詢:

==>  Preparing: select * from USERS WHERE ID = ? 
==> Parameters: 1(Integer)
<==      Total: 1
User{id=1, name='format', age=23, birthday=Sun Oct 12 23:20:13 CST 2014}
==>  Preparing: select * from USERS WHERE ID = ? 
==> Parameters: 2(Integer)
<==      Total: 1
User{id=2, name='FFF', age=50, birthday=Sat Dec 06 17:12:01 CST 2014}

不同session,進行相同查詢:

@Test
public void test() {
    SqlSession sqlSession = sqlSessionFactory.openSession();
    SqlSession sqlSession2 = sqlSessionFactory.openSession();
    try {
        User user = (User)sqlSession.selectOne("org.format.mybatis.cache.UserMapper.getById", 1);
        log.debug(user);
        User user2 = (User)sqlSession2.selectOne("org.format.mybatis.cache.UserMapper.getById", 1);
        log.debug(user2);
    } finally {
        sqlSession.close();
        sqlSession2.close();
    }
}

MyBatis進行了兩次資料庫查詢:

==>  Preparing: select * from USERS WHERE ID = ? 
==> Parameters: 1(Integer)
<==      Total: 1
User{id=1, name='format', age=23, birthday=Sun Oct 12 23:20:13 CST 2014}
==>  Preparing: select * from USERS WHERE ID = ? 
==> Parameters: 1(Integer)
<==      Total: 1
User{id=1, name='format', age=23, birthday=Sun Oct 12 23:20:13 CST 2014}

同個session,查詢之後更新資料,再次查詢相同的語句:

@Test
public void test() {
    SqlSession sqlSession = sqlSessionFactory.openSession();
    try {
        User user = (User)sqlSession.selectOne("org.format.mybatis.cache.UserMapper.getById", 1);
        log.debug(user);
        user.setAge(100);
        sqlSession.update("org.format.mybatis.cache.UserMapper.update", user);
        User user2 = (User)sqlSession.selectOne("org.format.mybatis.cache.UserMapper.getById", 1);
        log.debug(user2);
        sqlSession.commit();
    } finally {
        sqlSession.close();
    }
}

更新操作之後快取會被清除:

==>  Preparing: select * from USERS WHERE ID = ? 
==> Parameters: 1(Integer)
<==      Total: 1
User{id=1, name='format', age=23, birthday=Sun Oct 12 23:20:13 CST 2014}
==>  Preparing: update USERS SET NAME = ? , AGE = ? , BIRTHDAY = ? where ID = ? 
==> Parameters: format(String), 23(Integer), 2014-10-12 23:20:13.0(Timestamp), 1(Integer)
<==    Updates: 1
==>  Preparing: select * from USERS WHERE ID = ? 
==> Parameters: 1(Integer)
<==      Total: 1
User{id=1, name='format', age=23, birthday=Sun Oct 12 23:20:13 CST 2014}

很明顯,結果驗證了一級快取的概念,在同個SqlSession中,查詢語句相同的sql會被快取,但是一旦執行新增或更新或刪除操作,快取就會被清除

原始碼分析

在分析MyBatis的一級快取之前,我們先簡單看下MyBatis中幾個重要的類和介面:

org.apache.ibatis.session.Configuration類:MyBatis全域性配置資訊類

org.apache.ibatis.session.SqlSessionFactory介面:操作SqlSession的工廠介面,具體的實現類是DefaultSqlSessionFactory

org.apache.ibatis.session.SqlSession介面:執行sql,管理事務的介面,具體的實現類是DefaultSqlSession

org.apache.ibatis.Executor.Executor介面:sql執行器,SqlSession執行sql最終是通過該介面實現的,常用的實現類有SimpleExecutor和CachingExecutor,這些實現類都使用了裝飾者設計模式

一級快取的作用域是SqlSession,那麼我們就先看一下SqlSession的select過程:

這是DefaultSqlSession(SqlSession介面實現類,MyBatis預設使用這個類)的selectList原始碼(我們例子上使用的是selectOne方法,呼叫selectOne方法最終會執行selectList方法):

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

我們看到SqlSession最終會呼叫Executor介面的方法。

接下來我們看下DefaultSqlSession中的executor介面屬性具體是哪個實現類。

DefaultSqlSession的構造過程(DefaultSqlSessionFactory內部):

private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
    Transaction tx = null;
    try {
      final Environment environment = configuration.getEnvironment();
      final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
      tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
      final Executor executor = configuration.newExecutor(tx, execType, autoCommit);
      return new DefaultSqlSession(configuration, executor);
    } catch (Exception e) {
      closeTransaction(tx); // may have fetched a connection so lets call close()
      throw ExceptionFactory.wrapException("Error opening session.  Cause: " + e, e);
    } finally {
      ErrorContext.instance().reset();
    }
}

我們看到DefaultSqlSessionFactory構造DefaultSqlSession的時候,Executor介面的實現類是由Configuration構造的:

public Executor newExecutor(Transaction transaction, ExecutorType executorType, boolean autoCommit) {
    executorType = executorType == null ? defaultExecutorType : executorType;
    executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
    Executor executor;
    if (ExecutorType.BATCH == executorType) {
      executor = new BatchExecutor(this, transaction);
    } else if (ExecutorType.REUSE == executorType) {
      executor = new ReuseExecutor(this, transaction);
    } else {
      executor = new SimpleExecutor(this, transaction);
    }
    if (cacheEnabled) {
      executor = new CachingExecutor(executor, autoCommit);
    }
    executor = (Executor) interceptorChain.pluginAll(executor);
    return executor;
}

Executor根據ExecutorType的不同而建立,最常用的是SimpleExecutor,本文的例子也是建立這個實現類。 最後我們發現如果cacheEnabled這個屬性為true的話,那麼executor會被包一層裝飾器,這個裝飾器是CachingExecutor。其中cacheEnabled這個屬性是mybatis總配置檔案中settings節點中cacheEnabled子節點的值,預設就是true,也就是說我們在mybatis總配置檔案中不配cacheEnabled的話,它也是預設為開啟的。

現在,問題就剩下一個了,CachingExecutor執行sql的時候到底做了什麼?

帶著這個問題,我們繼續走下去(CachingExecutor的query方法):

public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
    Cache cache = ms.getCache();
    if (cache != null) {
      flushCacheIfRequired(ms);
      if (ms.isUseCache() && resultHandler == null) { 
        ensureNoOutParams(ms, parameterObject, boundSql);
        if (!dirty) {
          cache.getReadWriteLock().readLock().lock();
          try {
            @SuppressWarnings("unchecked")
            List<E> cachedList = (List<E>) cache.getObject(key);
            if (cachedList != null) return cachedList;
          } finally {
            cache.getReadWriteLock().readLock().unlock();
          }
        }
        List<E> list = delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
        tcm.putObject(cache, key, list); // issue #578. Query must be not synchronized to prevent deadlocks
        return list;
      }
    }
    return delegate.<E>query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
}

其中Cache cache = ms.getCache();這句程式碼中,這個cache實際上就是個二級快取,由於我們沒有開啟二級快取(二級快取的內容下面會分析),因此這裡執行了最後一句話。這裡的delegate也就是SimpleExecutor,SimpleExecutor沒有Override父類的query方法,因此最終執行了SimpleExecutor的父類BaseExecutor的query方法。

所以一級快取最重要的程式碼就是BaseExecutor的query方法!

通過原始碼分析MyBatis的快取0

BaseExecutor的屬性localCache是個PerpetualCache型別的例項,PerpetualCache類是實現了MyBatis的Cache快取介面的實現類之一,內部有個Map 型別的屬性用來儲存快取資料。 這個localCache的型別在BaseExecutor內部是寫死的。 這個localCache就是一級快取!

接下來我們看下為何執行新增或更新或刪除操作,一級快取就會被清除這個問題。

首先MyBatis處理新增或刪除的時候,最終都是呼叫update方法,也就是說新增或者刪除操作在MyBatis眼裡都是一個更新操作。

我們看下DefaultSqlSession的update方法:

public int update(String statement, Object parameter) {
    try {
      dirty = true;
      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();
    }
}

很明顯,這裡呼叫了CachingExecutor的update方法:

public int update(MappedStatement ms, Object parameterObject) throws SQLException {
    flushCacheIfRequired(ms);
    return delegate.update(ms, parameterObject);
}

這裡的flushCacheIfRequired方法清除的是二級快取,我們之後會分析。 CachingExecutor委託給了(之前已經分析過)SimpleExecutor的update方法,SimpleExecutor沒有Override父類BaseExecutor的update方法,因此我們看BaseExecutor的update方法:

public int update(MappedStatement ms, Object parameter) throws SQLException {
    ErrorContext.instance().resource(ms.getResource()).activity("executing an update").object(ms.getId());
    if (closed) throw new ExecutorException("Executor was closed.");
    clearLocalCache();
    return doUpdate(ms, parameter);
}

我們看到了關鍵的一句程式碼: clearLocalCache(); 進去看看:

public void clearLocalCache() {
    if (!closed) {
      localCache.clear();
      localOutputParameterCache.clear();
    }
}

沒錯,就是這條,sqlsession沒有關閉的話,進行新增、刪除、修改操作的話就是清除一級快取,也就是SqlSession的快取。

二級快取

二級快取的作用域是全域性,換句話說,二級快取已經脫離SqlSession的控制了。

在測試二級快取之前,我先把結論說一下:

二級快取的作用域是全域性的,二級快取在SqlSession關閉或提交之後才會生效。

在分析MyBatis的二級快取之前,我們先簡單看下MyBatis中一個關於二級快取的類(其他相關的類和介面之前已經分析過):

org.apache.ibatis.mapping.MappedStatement:

MappedStatement類在Mybatis框架中用於表示XML檔案中一個sql語句節點,即一個<select />、<update />或者<insert />標籤。Mybatis框架在初始化階段會對XML配置檔案進行讀取,將其中的sql語句節點物件化為一個個MappedStatement物件。

配置

二級快取跟一級快取不同,一級快取不需要配置任何東西,且預設開啟。 二級快取就需要配置一些東西。

本文就說下最簡單的配置,在mapper檔案上加上這句配置即可:

<cache/>

其實二級快取跟3個配置有關:

  1. mybatis全域性配置檔案中的setting中的cacheEnabled需要為true(預設為true,不設定也行)
  2. mapper配置檔案中需要加入<cache>節點
  3. mapper配置檔案中的select節點需要加上屬性useCache需要為true(預設為true,不設定也行)

測試

不同SqlSession,查詢相同語句,第一次查詢之後commit SqlSession:

@Test
public void testCache2() {
    SqlSession sqlSession = sqlSessionFactory.openSession();
    SqlSession sqlSession2 = sqlSessionFactory.openSession();
    try {
        String sql = "org.format.mybatis.cache.UserMapper.getById";
        User user = (User)sqlSession.selectOne(sql, 1);
        log.debug(user);
		// 注意,這裡一定要提交。 不提交還是會查詢兩次資料庫
        sqlSession.commit();
        User user2 = (User)sqlSession2.selectOne(sql, 1);
        log.debug(user2);
    } finally {
        sqlSession.close();
        sqlSession2.close();
    }
}

MyBatis僅進行了一次資料庫查詢:

==>  Preparing: select * from USERS WHERE ID = ? 
==> Parameters: 1(Integer)
<==      Total: 1
User{id=1, name='format', age=23, birthday=Sun Oct 12 23:20:13 CST 2014}
User{id=1, name='format', age=23, birthday=Sun Oct 12 23:20:13 CST 2014}

不同SqlSession,查詢相同語句,第一次查詢之後close SqlSession:

@Test
public void testCache2() {
    SqlSession sqlSession = sqlSessionFactory.openSession();
    SqlSession sqlSession2 = sqlSessionFactory.openSession();
    try {
        String sql = "org.format.mybatis.cache.UserMapper.getById";
        User user = (User)sqlSession.selectOne(sql, 1);
        log.debug(user);
        sqlSession.close();
        User user2 = (User)sqlSession2.selectOne(sql, 1);
        log.debug(user2);
    } finally {
        sqlSession2.close();
    }
}

MyBatis僅進行了一次資料庫查詢:

==>  Preparing: select * from USERS WHERE ID = ? 
==> Parameters: 1(Integer)
<==      Total: 1
User{id=1, name='format', age=23, birthday=Sun Oct 12 23:20:13 CST 2014}
User{id=1, name='format', age=23, birthday=Sun Oct 12 23:20:13 CST 2014}

不同SqlSesson,查詢相同語句。 第一次查詢之後SqlSession不提交:

@Test
public void testCache2() {
    SqlSession sqlSession = sqlSessionFactory.openSession();
    SqlSession sqlSession2 = sqlSessionFactory.openSession();
    try {
        String sql = "org.format.mybatis.cache.UserMapper.getById";
        User user = (User)sqlSession.selectOne(sql, 1);
        log.debug(user);
        User user2 = (User)sqlSession2.selectOne(sql, 1);
        log.debug(user2);
    } finally {
        sqlSession.close();
        sqlSession2.close();
    }
}

MyBatis執行了兩次資料庫查詢:

==>  Preparing: select * from USERS WHERE ID = ? 
==> Parameters: 1(Integer)
<==      Total: 1
User{id=1, name='format', age=23, birthday=Sun Oct 12 23:20:13 CST 2014}
==>  Preparing: select * from USERS WHERE ID = ? 
==> Parameters: 1(Integer)
<==      Total: 1
User{id=1, name='format', age=23, birthday=Sun Oct 12 23:20:13 CST 2014}

原始碼分析

我們從在mapper檔案中加入的<cache/>中開始分析原始碼,關於MyBatis的SQL解析請參考另外一篇部落格Mybatis解析動態sql原理分析。接下來我們看下這個cache的解析:

XMLMappedBuilder(解析每個mapper配置檔案的解析類,每一個mapper配置都會例項化一個XMLMapperBuilder類)的解析方法:

private void configurationElement(XNode context) {
    try {
      String namespace = context.getStringAttribute("namespace");
      if (namespace.equals("")) {
          throw new BuilderException("Mapper's namespace cannot be empty");
      }
      builderAssistant.setCurrentNamespace(namespace);
      cacheRefElement(context.evalNode("cache-ref"));
      cacheElement(context.evalNode("cache"));
      parameterMapElement(context.evalNodes("/mapper/parameterMap"));
      resultMapElements(context.evalNodes("/mapper/resultMap"));
      sqlElement(context.evalNodes("/mapper/sql"));
      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) {
      String type = context.getStringAttribute("type", "PERPETUAL");
      Class<? extends Cache> typeClass = typeAliasRegistry.resolveAlias(type);
      String eviction = context.getStringAttribute("eviction", "LRU");
      Class<? extends Cache> evictionClass = typeAliasRegistry.resolveAlias(eviction);
      Long flushInterval = context.getLongAttribute("flushInterval");
      Integer size = context.getIntAttribute("size");
      boolean readWrite = !context.getBooleanAttribute("readOnly", false);
      Properties props = context.getChildrenAsProperties();
      builderAssistant.useNewCache(typeClass, evictionClass, flushInterval, size, readWrite, props);
    }
}

解析完cache標籤之後會使用builderAssistant的userNewCache方法,這裡的builderAssistant是一個MapperBuilderAssistant型別的幫助類,每個XMLMappedBuilder構造的時候都會例項化這個屬性,MapperBuilderAssistant類內部有個Cache型別的currentCache屬性,這個屬性也就是mapper配置檔案中cache節點所代表的值:

public Cache useNewCache(Class<? extends Cache> typeClass,
  Class<? extends Cache> evictionClass,
  Long flushInterval,
  Integer size,
  boolean readWrite,
  Properties props) {
    typeClass = valueOrDefault(typeClass, PerpetualCache.class);
    evictionClass = valueOrDefault(evictionClass, LruCache.class);
    Cache cache = new CacheBuilder(currentNamespace)
        .implementation(typeClass)
        .addDecorator(evictionClass)
        .clearInterval(flushInterval)
        .size(size)
        .readWrite(readWrite)
        .properties(props)
        .build();
    configuration.addCache(cache);
    currentCache = cache;
    return cache;
}

ok,現在mapper配置檔案中的cache節點被解析到了XMLMapperBuilder例項中的builderAssistant屬性中的currentCache值裡。

接下來XMLMapperBuilder會解析select節點,解析select節點的時候使用XMLStatementBuilder進行解析(也包括其他insert,update,delete節點):

public void parseStatementNode() {
    String id = context.getStringAttribute("id");
    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");
    LanguageDriver langDriver = getLanguageDriver(lang);

    Class<?> resultTypeClass = resolveClass(resultType);
    String resultSetType = context.getStringAttribute("resultSetType");
    StatementType statementType = StatementType.valueOf(context.getStringAttribute("statementType", StatementType.PREPARED.toString()));
    ResultSetType resultSetTypeEnum = resolveResultSetType(resultSetType);

    String nodeName = context.getNode().getNodeName();
    SqlCommandType sqlCommandType = SqlCommandType.valueOf(nodeName.toUpperCase(Locale.ENGLISH));
    boolean isSelect = sqlCommandType == SqlCommandType.SELECT;
    boolean flushCache = context.getBooleanAttribute("flushCache", !isSelect);
    boolean useCache = context.getBooleanAttribute("useCache", isSelect);
    boolean resultOrdered = context.getBooleanAttribute("resultOrdered", false);

    // Include Fragments before parsing
    XMLIncludeTransformer includeParser = new XMLIncludeTransformer(configuration, builderAssistant);
    includeParser.applyIncludes(context.getNode());

    // Parse selectKey after includes and remove them.
    processSelectKeyNodes(id, parameterTypeClass, langDriver);

    // Parse the SQL (pre: <selectKey> and <include> were parsed and removed)
    SqlSource sqlSource = langDriver.createSqlSource(configuration, context, parameterTypeClass);
    String resultSets = context.getStringAttribute("resultSets");
    String keyProperty = context.getStringAttribute("keyProperty");
    String keyColumn = context.getStringAttribute("keyColumn");
    KeyGenerator keyGenerator;
    String keyStatementId = id + SelectKeyGenerator.SELECT_KEY_SUFFIX;
    keyStatementId = builderAssistant.applyCurrentNamespace(keyStatementId, true);
    if (configuration.hasKeyGenerator(keyStatementId)) {
      keyGenerator = configuration.getKeyGenerator(keyStatementId);
    } else {
      keyGenerator = context.getBooleanAttribute("useGeneratedKeys",
          configuration.isUseGeneratedKeys() && SqlCommandType.INSERT.equals(sqlCommandType))
          ? new Jdbc3KeyGenerator() : new NoKeyGenerator();
    }

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

這段程式碼前面都是解析一些標籤的屬性,我們看到了最後一行使用builderAssistant新增MappedStatement,其中builderAssistant屬性是構造XMLStatementBuilder的時候通過XMLMappedBuilder傳入的,我們繼續看builderAssistant的addMappedStatement方法:

通過原始碼分析MyBatis的快取1

進入setStatementCache:

private void setStatementCache(
  boolean isSelect,
  boolean flushCache,
  boolean useCache,
  Cache cache,
  MappedStatement.Builder statementBuilder) {
    flushCache = valueOrDefault(flushCache, !isSelect);
    useCache = valueOrDefault(useCache, isSelect);
    statementBuilder.flushCacheRequired(flushCache);
    statementBuilder.useCache(useCache);
    statementBuilder.cache(cache);
}

最終mapper配置檔案中的<cache/>被設定到了XMLMapperBuilder的builderAssistant屬性中,XMLMapperBuilder中使用XMLStatementBuilder遍歷CRUD節點,遍歷CRUD節點的時候將這個cache節點設定到這些CRUD節點中,這個cache就是所謂的二級快取!

接下來我們回過頭來看查詢的原始碼,CachingExecutor的query方法:

通過原始碼分析MyBatis的快取2

進入TransactionalCacheManager的putObject方法:

public void putObject(Cache cache, CacheKey key, Object value) {
	getTransactionalCache(cache).putObject(key, value);
}

private TransactionalCache getTransactionalCache(Cache cache) {
    TransactionalCache txCache = transactionalCaches.get(cache);
    if (txCache == null) {
      txCache = new TransactionalCache(cache);
      transactionalCaches.put(cache, txCache);
    }
    return txCache;
}

TransactionalCache的putObject方法:

public void putObject(Object key, Object object) {
    entriesToRemoveOnCommit.remove(key);
    entriesToAddOnCommit.put(key, new AddEntry(delegate, key, object));
}

我們看到,資料被加入到了entriesToAddOnCommit中,這個entriesToAddOnCommit是什麼東西呢,它是TransactionalCache的一個Map屬性:

private Map<Object, AddEntry> entriesToAddOnCommit;

AddEntry是TransactionalCache內部的一個類:

private static class AddEntry {
    private Cache cache;
    private Object key;
    private Object value;

    public AddEntry(Cache cache, Object key, Object value) {
      this.cache = cache;
      this.key = key;
      this.value = value;
    }

    public void commit() {
      cache.putObject(key, value);
    }
}

好了,現在我們發現使用二級快取之後:查詢資料的話,先從二級快取中拿資料,如果沒有的話,去一級快取中拿,一級快取也沒有的話再查詢資料庫。有了資料之後在丟到TransactionalCache這個物件的entriesToAddOnCommit屬性中。

接下來我們來驗證為什麼SqlSession commit或close之後,二級快取才會生效這個問題。

DefaultSqlSession的commit方法:

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方法:

public void commit(boolean required) throws SQLException {
    delegate.commit(required);
    tcm.commit();
    dirty = false;
}

tcm.commit即 TransactionalCacheManager的commit方法:

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

TransactionalCache的commit方法:

public void commit() {
    delegate.getReadWriteLock().writeLock().lock();
    try {
      if (clearOnCommit) {
        delegate.clear();
      } else {
        for (RemoveEntry entry : entriesToRemoveOnCommit.values()) {
          entry.commit();
        }
      }
      for (AddEntry entry : entriesToAddOnCommit.values()) {
        entry.commit();
      }
      reset();
    } finally {
      delegate.getReadWriteLock().writeLock().unlock();
    }
}

發現呼叫了AddEntry的commit方法:

public void commit() {
  cache.putObject(key, value);
}

發現了! AddEntry的commit方法會把資料丟到cache中,也就是丟到二級快取中!

關於為何呼叫close方法後,二級快取才會生效,因為close方法內部會呼叫commit方法。本文就不具體說了。 讀者有興趣的話看一看原始碼就知道為什麼了。

其他

Cache介面簡介

org.apache.ibatis.cache.Cache是MyBatis的快取介面,想要實現自定義的快取需要實現這個介面。

MyBatis中關於Cache介面的實現類也使用了裝飾者設計模式

我們看下它的一些實現類:

通過原始碼分析MyBatis的快取3

簡單說明:

LRU ? 最近最少使用的:移除最長時間不被使用的物件。

FIFO ? 先進先出:按物件進入快取的順序來移除它們。

SOFT ? 軟引用:移除基於垃圾回收器狀態和軟引用規則的物件。

WEAK ? 弱引用:更積極地移除基於垃圾收集器狀態和弱引用規則的物件。

<cache
  eviction="FIFO"
  flushInterval="60000"
  size="512"
  readOnly="true"/>

可以通過cache節點的eviction屬性設定,也可以設定其他的屬性。

cache-ref節點

mapper配置檔案中還可以加入cache-ref節點,它有個屬性namespace。

如果每個mapper檔案都是用cache-ref,且namespace都一樣,那麼就代表著真正意義上的全域性快取。

如果只用了cache節點,那僅代表這個這個mapper內部的查詢被快取了,其他mapper檔案的不起作用,這並不是所謂的全域性快取。

總結

總體來說,MyBatis的原始碼看起來還是比較輕鬆的,本文從實踐和原始碼方面深入分析了MyBatis的快取原理,希望對讀者有幫助。 下一篇文章我將分析Spring跟MyBatis結合之後快取的使用原理分析。

相關文章