一、 一级缓存

  1. SqlSession 级别的缓存,MyBatis **默认开启了一级缓存**,一级缓存是在SqlSession 层面进行缓存的。即,同一个SqlSession ,多次调用同一个Mapper和同一个方法的同一个参数,只会进行一次数据库查询,然后把数据缓存到缓冲中,以后直接先从缓存中取出数据,不会直接去查数据库。<br /> 但是不同的SqlSession对象,因为不同的SqlSession都是相互隔离的,所以相同的Mapper、参数和方法,他还是会再次发送到SQL到数据库去执行,返回结果。 <br />每个SqlSession中持有了Executor,每个Executor中有一个LocalCache。当用户发起查询时,MyBatis根据当前执行的语句生成`MappedStatement`,在Local Cache进行查询,如果缓存命中的话,直接返回结果给用户,如果缓存没有命中的话,查询数据库,结果写入`Local Cache`<br />**一级缓存配置**<br />我们来看看如何使用MyBatis一级缓存。开发者只需在MyBatis的配置文件中,添加如下语句,就可以使用一级缓存。共有两个选项,`SESSION`或者`STATEMENT`,默认是`SESSION`级别,即在一个MyBatis会话中执行的所有语句,都会共享这一个缓存。一种是`STATEMENT`级别,可以理解为缓存只对当前执行的这一个`Statement`有效。可以参考上面的参数配置
<setting name="localCacheScope" value="SESSION"/>

问题:由于Sqlsession的cache更新不及时会导致读脏数据(两个sqlsession 都缓存了相同的数据,其中一个更改了,另外一个继续使用缓存中的数据)。

SqlSession: 对外提供了用户和数据库之间交互需要的所有方法,隐藏了底层的细节。默认实现类是DefaultSqlSession。
Executor: SqlSession向用户提供操作数据库的方法,但和数据库操作有关的职责都会委托给Executor。
Executor有若干子类

**

Mybaties的缓存学习( 拓展一) - 图1

  • BaseExecutor

BaseExecutor是一个实现了Executor接口的抽象类,定义若干抽象方法,在执行的时候,把具体的操作委托给子类进行执行。自己实现了部分代码

/**
部分需要实现的代码
*/public abstract class BaseExecutor implements Executor {

    private static final Log log = LogFactory.getLog(BaseExecutor.class);

    protected Transaction transaction;
    protected Executor wrapper;

    protected ConcurrentLinkedQueue<DeferredLoad> deferredLoads;
    // 注意这个成员变量,对cache的查询和写入
    protected PerpetualCache localCache;
    protected PerpetualCache localOutputParameterCache;
    protected Configuration configuration;

    protected int queryStack;
    private boolean closed;
    ...
    protected abstract int doUpdate(MappedStatement ms, Object parameter) throws SQLException;
    protected abstract List<BatchResult> doFlushStatements(boolean isRollback) throws SQLException;
    protected abstract <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException;
    protected abstract <E> Cursor<E> doQueryCursor(MappedStatement ms, Object parameter, RowBounds rowBounds, BoundSql boundSql) throws SQLException;

    ....
}

Cache 接口类
Mybaties的缓存学习( 拓展一) - 图2

有若干个实现类,使用装饰器模式互相组装,提供丰富的操控缓存的能力,部分实现类如下图所示:

Mybaties的缓存学习( 拓展一) - 图3

这里主要看PerpetualCache

public class PerpetualCache implements Cache {

  private final String id;

  //一级缓存的操作主要就是针对hashMap的操作
  private Map<Object, Object> cache = new HashMap<Object, Object>();

  public PerpetualCache(String id) {
    this.id = id;
  }
    .....
}

分析执行过程,找到一级缓存使用的位置
为执行和数据库的交互,首先需要初始化SqlSession,通过DefaultSqlSessionFactory开启SqlSession

sqlSessionFactory.openSession();
//调用默认的DefaultSqlSessionFactory
    @Override
      public SqlSession openSession() {
    return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
  }

  //然后开启Session,中间会创建一个Excute,因为重点分析一级缓存,所以找它
    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);
      return new DefaultSqlSession(configuration, executor, autoCommit);
    } 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();
    }
  }    

 //调用Configuration的newExecutor()    
    //根据类型创建
    public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
        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);
        }
        //注意这里,如果二级缓存开关开启的话,是使用CachingExecutor装饰BaseExecutor的子类
        if (cacheEnabled) {
          executor = new CachingExecutor(executor);
        }
        executor = (Executor) interceptorChain.pluginAll(executor);
        return executor;
  }
//到这里我们就创建了Sqlsession,然后根据select、insert、update、delet


//如果是查询,会执行这个
    @Override
      public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
        try {
           //根据映射语句的Id获得语句,就是便签里面填的那个id
          MappedStatement ms = configuration.getMappedStatement(statement);
            //把任务交给了executor
          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();
        }
      }

//SqlSession把具体的查询职责委托给了Executor。如果只开启了一级缓存的话,首先会进入BaseExecutor的query方法。
//MappedStatement -》映射语句
@Override
  public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
    BoundSql boundSql = ms.getBoundSql(parameter);
    //生成缓存key
    CacheKey key = createCacheKey(ms, parameter, rowBounds, boundSql);
    return query(ms, parameter, rowBounds, resultHandler, key, boundSql);
 }
  //生成CacheKey ,对比出基本的信息,也就是对下面传入的参数进行比较
@Override
  public CacheKey createCacheKey(MappedStatement ms, Object parameterObject, RowBounds rowBounds, BoundSql boundSql) {
    if (closed) {
      throw new ExecutorException("Executor was closed.");
    }
      CacheKey cacheKey = new CacheKey();
      cacheKey.update(ms.getId());
      cacheKey.update(rowBounds.getOffset());
      cacheKey.update(rowBounds.getLimit());
      cacheKey.update(boundSql.getSql());
      //后面都是参数映射
      ...
          cacheKey.update(value);
  }
//首先是成员变量和构造函数,有一个初始的hachcode和乘数,同时维护了一个内部的updatelist。在CacheKey的update方法中,会进行一个hashcode和checksum的计算,同时把传入的参数添加进updatelist中
// 发现比较方法和更新方法
public class CacheKey implements Cloneable, Serializable {
public static final CacheKey NULL_CACHE_KEY = new NullCacheKey();

    private static final int DEFAULT_MULTIPLYER = 37;
    private static final int DEFAULT_HASHCODE = 17;

    private final int multiplier;
    private int hashcode;
    private long checksum;
    private int count;
    private transient List<Object> updateList;
    public void update(Object object) {
        int baseHashCode = object == null ? 1 : ArrayUtil.hashCode(object); 

        count++;
        checksum += baseHashCode;
        baseHashCode *= count;

        hashcode = multiplier * hashcode + baseHashCode;

        updateList.add(object);
    }

    //重写了equals方法,
    /**
    *除去hashcode、checksum和count的比较外,只要updatelist中的元素一一对应相等,
    * 那么就可以认为是CacheKey相等。只要两条SQL的下列五个值相同,即可以认为是相同的SQL。
    *  Statement Id + Offset + Limmit + Sql + Params,就是前面传入的那几个
    */
    @Override
    public boolean equals(Object object) {
        if (this == object) {
            return true;
        }
        if (!(object instanceof CacheKey)) {
            return false;
        }

        final CacheKey cacheKey = (CacheKey) object;

        if (hashcode != cacheKey.hashcode) {
            return false;
        }
        if (checksum != cacheKey.checksum) {
            return false;
        }
        if (count != cacheKey.count) {
            return false;
        }

        for (int i = 0; i < updateList.size(); i++) {
            Object thisObject = updateList.get(i);
            Object thatObject = cacheKey.updateList.get(i);
            if (!ArrayUtil.equals(thisObject, thatObject)) {
                return false;
            }
        }
        return true;
    }
}

// query继续往下走
    @Override
      public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
        BoundSql boundSql = ms.getBoundSql(parameter);
        CacheKey key = createCacheKey(ms, parameter, rowBounds, boundSql);
        //走到这里了,继续
        return query(ms, parameter, rowBounds, resultHandler, key, boundSql);
     }

    @Override
  public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
    ErrorContext.instance().resource(ms.getResource()).activity("executing a query").object(ms.getId());
    if (closed) {
      throw new ExecutorException("Executor was closed.");
    }
    if (queryStack == 0 && ms.isFlushCacheRequired()) {
      clearLocalCache();
    }
    List<E> list;
    try {
      queryStack++;
       //先从缓存中查询
      list = resultHandler == null ? (List<E>) localCache.getObject(key) : null;
       //这个主要是处理存储过程用的。
      if (list != null) {
        handleLocallyCachedOutputParameters(ms, key, parameter, boundSql);
      } else {
         //查询不到,进入数据库查询,同时在这里也会对localCache进行写入
        list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);
      }
    } finally {
      queryStack--;
    }
    if (queryStack == 0) {
      for (DeferredLoad deferredLoad : deferredLoads) {
        deferredLoad.load();
      }
      // issue #601
      deferredLoads.clear();

       // 这里判断一级缓存级别,如果是Statement那么清空缓存,所以无法共享缓存,每次都要重新查询
      if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) {
        // issue #482
        clearLocalCache();
      }
    }
    return list;
  }
/**同样看下insert、update的刷新行为***/
 // 在 DefaultSqlSession中
     @Override
      public int insert(String statement) {
        return insert(statement, null);
      }

      @Override
      public int insert(String statement, Object parameter) {
        return update(statement, parameter);
      }

      @Override
      public int update(String statement) {
        return update(statement, null);
      }

    //其中update 如下
    @Override
  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();
    }
  }
  //executor中执行
    @Override
  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);
  }






//queryFromDatabase 的过程
 private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
    List<E> list;
    localCache.putObject(key, EXECUTION_PLACEHOLDER);
    try {
      list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql);
    } finally {
      localCache.removeObject(key);
    }
     //这里对缓存进行了读写操作
    localCache.putObject(key, list);
    if (ms.getStatementType() == StatementType.CALLABLE) {
      localOutputParameterCache.putObject(key, parameter);
    }
    return list;
  }
  1. MyBatis一级缓存的生命周期和SqlSession一致。
  2. MyBatis一级缓存内部设计简单,只是一个没有容量限定的HashMap,在缓存的功能性上有所欠缺。
  3. MyBatis的一级缓存最大范围是SqlSession内部,有多个SqlSession或者分布式的环境下,数据库写操作会引起脏数据,建议设定缓存级别为Statement。

二、 二级缓存

一级缓存中,其最大的共享范围就是一个SqlSession内部,如果多个SqlSession之间需要共享缓存,则需要使用到二级缓存。开启二级缓存后,会使用CachingExecutor装饰Executor,进入一级缓存的查询流程前,先在CachingExecutor进行二级缓存的查询,具体的工作流程如下所示。
二级缓存开启后,同一个namespace下的所有操作语句,都影响着同一个Cache,即二级缓存被多个SqlSession共享,是一个全局的变量。
当开启缓存后,数据的查询执行的流程就是 二级缓存 -> 一级缓存 -> 数据库。Mybaties的缓存学习( 拓展一) - 图4

配置

    <setting name="cacheEnabled" value="true"/>

在mapper.xml中配置

<cache/>   
<!---引用别的命名空间的配置-->
<cache-ref namespace="mapper.StudentMapper"/>
  • type:cache使用的类型,默认是PerpetualCache,这在一级缓存中提到过。
  • eviction: 定义回收的策略,常见的有FIFO,LRU。
  • flushInterval: 配置一定时间自动刷新缓存,单位是毫秒。
  • size: 最多缓存对象的个数。
  • readOnly: 是否只读,若配置可读写,则需要对应的实体类能够序列化。
  • blocking: 若缓存中找不到对应的key,是否会一直blocking,直到有对应的数据进入缓存。

cache-ref代表引用别的命名空间的Cache配置,两个命名空间的操作使用的是同一个Cache。

问题:MyBatis的二级缓存不适应用于映射文件中存在多表查询的情况。
解决:可以使用Cache ref,让ClassMapper引用StudenMapper命名空间,这样两个映射文件对应的SQL操作都使用的是同一块缓存了
后果:缓存的粒度变粗了,多个Mapper namespace下的所有操作都会对缓存使用造成影响。
本质上是装饰器模式的使用,具体的装饰链:

SynchronizedCache -> LoggingCache -> SerializedCache -> LruCache -> PerpetualCache。

以下是具体这些Cache实现类的介绍,他们的组合为Cache赋予了不同的能力。

  • SynchronizedCache:同步Cache,实现比较简单,直接使用synchronized修饰方法。
  • LoggingCache:日志功能,装饰类,用于记录缓存的命中率,如果开启了DEBUG模式,则会输出命中率日志。
  • SerializedCache:序列化功能,将值序列化后存到缓存中。该功能用于缓存返回一份实例的Copy,用于保存线程安全。
  • LruCache:采用了Lru算法的Cache实现,移除最近最少使用的Key/Value。
  • PerpetualCache: 作为为最基础的缓存类,底层实现比较简单,直接使用了HashMap。

源码分析:
直接跳到CachingExecutor
CachingExecutor 是一个装饰器,里面的delegate就是Executor,并且是已经生分类生成的Exector。


 public class CachingExecutor implements Executor {

  private final Executor delegate;
   //tcm,事务性缓存管理器,里面还有个hashmap进行缓存,有更新等一些接口

  private final TransactionalCacheManager tcm = new TransactionalCacheManager();
   //带Exector的构造器
   public CachingExecutor(Executor delegate) {
    this.delegate = delegate;
    delegate.setExecutorWrapper(this);
  }
     ....
     @Override
  public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql)
      throws SQLException {
    //获得CachingExecutor的query方法,首先会从MappedStatement中获得在配置初始化时赋予的Cache。
     // 一些基本的设置
    Cache cache = ms.getCache();
    if (cache != null) {
        //判断是否需要刷新缓存,默认SELECT语句不需要刷新缓存,insert/update/delte会刷新缓存
      flushCacheIfRequired(ms);
      if (ms.isUseCache() && resultHandler == null) {
          //用来处理存储过程的,暂时不用考虑。
        ensureNoOutParams(ms, parameterObject, boundSql);
         //从tcm中获取缓存的列表
        @SuppressWarnings("unchecked")
        List<E> list = (List<E>) tcm.getObject(cache, key);
          /***
          //tcm 的hashMap 里面是一个个的TransactionalCache,它实现了Cache,所以又根据key来获得具体的信息
          public Object getObject(Cache cache, CacheKey key) {
                return getTransactionalCache(cache).getObject(key);
          }
         //put方法也不是直接操作缓存,只是在把这次的数据和key放入待提交的Map中。
         //所以不commit,不会对二级缓存造成直接影响
         @Override
        public void putObject(Object key, Object object) {
            entriesToAddOnCommit.put(key, object);
        }
          ***/
        if (list == null) {
            //如果查询到数据,则调用tcm.putObject方法,往缓存中放入值。
            //delegate就是Executor
          list = delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
          tcm.putObject(cache, key, list); // issue #578 and #116
        }
        return list;
      }
    }
    return delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
  }
     ...
 }
// 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
@Override
  public void commit(boolean required) throws SQLException {
    delegate.commit(required);
    tcm.commit();
  }


// tcm
public void commit() {
    for (TransactionalCache txCache : transactionalCaches.values()) {
      txCache.commit();
    }
  }
//TransactionalCache
//TrancationalCache的clear方法设置的标志位,真正的清理Cache是放到这里来进行的。
//具体清理的职责委托给了包装的Cache类。之后进入flushPendingEntries方法。
public void commit() {
    //清除刷新
    if (clearOnCommit) {
      delegate.clear();
    }
    //这里才是刷新
    flushPendingEntries();
    reset();
  }

//如果是insert|update|delete的话,会统一进入CachingExecutor的update方法,其中调用了这个函数
//CachingExecutor中
@Override
  public int update(MappedStatement ms, Object parameterObject) throws SQLException {
      //刷新
    flushCacheIfRequired(ms);
    return delegate.update(ms, parameterObject);
  }

二级缓存执行流程后就会进入一级缓存的执行流程
总结:

  1. MyBatis的二级缓存相对于一级缓存来说,实现了SqlSession之间缓存数据的共享,同时粒度更加的细,能够到namespace级别,通过Cache接口实现类不同的组合,对Cache的可控性也更强。
  2. MyBatis在多表查询时,极大可能会出现脏数据,有设计上的缺陷,安全使用二级缓存的条件比较苛刻。
  3. 在分布式环境下,由于默认的MyBatis Cache实现都是基于本地的,分布式环境下必然会出现读取到脏数据,需要使用集中式缓存将MyBatis的Cache接口实现,有一定的开发成本,直接使用Redis、Memcached等分布式缓存可能成本更低,安全性也更高。
 本文对介绍了MyBatis一二级缓存的基本概念,并从应用及源码的角度对MyBatis的缓存机制进行了分析。最后对MyBatis缓存机制做了一定的总结,个人建议MyBatis缓存特性在生产环境中进行关闭,单纯作为一个ORM框架使用可能更为合适。([抄自](https://tech.meituan.com/2018/01/19/mybatis-cache.html))