如下内容来自美团技术博客:聊聊MyBatis缓存机制html
MyBatis是常见的Java数据库访问层框架。在平常工做中,开发人员多数状况下是使用MyBatis的默认缓存配置,可是MyBatis缓存机制有一些不足之处,在使用中容易引发脏数据,造成一些潜在的隐患。我的在业务开发中也处理过一些因为MyBatis缓存引起的开发问题,带着我的的兴趣,但愿从应用及源码的角度为读者梳理MyBatis缓存机制。
本次分析中涉及到的代码和数据库表均放在GitHub上,地址: mybatis-cache-demo 。git
本文按照如下顺序展开。github
在应用运行过程当中,咱们有可能在一次数据库会话中,执行屡次查询条件彻底相同的SQL,MyBatis提供了一级缓存的方案优化这部分场景,若是是相同的SQL语句,会优先命中一级缓存,避免直接对数据库进行查询,提升性能。具体执行过程以下图所示。
每一个SqlSession中持有了Executor,每一个Executor中有一个LocalCache。当用户发起查询时,MyBatis根据当前执行的语句生成MappedStatement,在Local Cache进行查询,若是缓存命中的话,直接返回结果给用户,若是缓存没有命中的话,查询数据库,结果写入Local Cache,最后返回结果给用户。具体实现类的类关系图以下图所示。
算法
咱们来看看如何使用MyBatis一级缓存。开发者只需在MyBatis的配置文件中,添加以下语句,就可使用一级缓存。共有两个选项,SESSION或者STATEMENT,默认是SESSION级别,即在一个MyBatis会话中执行的全部语句,都会共享这一个缓存。一种是STATEMENT级别,能够理解为缓存只对当前执行的这一个Statement有效。sql
<setting name="localCacheScope" value="SESSION"/>
接下来经过实验,了解MyBatis一级缓存的效果,每一个单元测试后都请恢复被修改的数据。
首先是建立示例表student,建立对应的POJO类和增改的方法,具体能够在entity包和mapper包中查看。数据库
CREATE TABLE `student` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(200) COLLATE utf8_bin DEFAULT NULL, `age` tinyint(3) unsigned DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
在如下实验中,id为1的学生名称是凯伦。后端
实验1缓存
开启一级缓存,范围为会话级别,调用三次getStudentById,代码以下所示:安全
public void getStudentById() throws Exception { SqlSession sqlSession = factory.openSession(true); // 自动提交事务 StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class); System.out.println(studentMapper.getStudentById(1)); System.out.println(studentMapper.getStudentById(1)); System.out.println(studentMapper.getStudentById(1)); }
执行结果:
咱们能够看到,只有第一次真正查询了数据库,后续的查询使用了一级缓存。session
实验2
增长了对数据库的修改操做,验证在一次数据库会话中,若是对数据库发生了修改操做,一级缓存是否会失效。
@Test public void addStudent() throws Exception { SqlSession sqlSession = factory.openSession(true); // 自动提交事务 StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class); System.out.println(studentMapper.getStudentById(1)); System.out.println("增长了" + studentMapper.addStudent(buildStudent()) + "个学生"); System.out.println(studentMapper.getStudentById(1)); sqlSession.close(); }
执行结果:
咱们能够看到,在修改操做后执行的相同查询,查询了数据库,一级缓存失效。
实验3
开启两个SqlSession,在sqlSession1中查询数据,使一级缓存生效,在sqlSession2中更新数据库,验证一级缓存只在数据库会话内部共享。
@Test public void testLocalCacheScope() throws Exception { SqlSession sqlSession1 = factory.openSession(true); SqlSession sqlSession2 = factory.openSession(true); StudentMapper studentMapper = sqlSession1.getMapper(StudentMapper.class); StudentMapper studentMapper2 = sqlSession2.getMapper(StudentMapper.class); System.out.println("studentMapper读取数据: " + studentMapper.getStudentById(1)); System.out.println("studentMapper读取数据: " + studentMapper.getStudentById(1)); System.out.println("studentMapper2更新了" + studentMapper2.updateStudentName("小岑",1) + "个学生的数据"); System.out.println("studentMapper读取数据: " + studentMapper.getStudentById(1)); System.out.println("studentMapper2读取数据: " + studentMapper2.getStudentById(1)); }
sqlSession2更新了id为1的学生的姓名,从凯伦改成了小岑,但session1以后的查询中,id为1的学生的名字仍是凯伦,出现了脏数据,也证实了以前的设想,一级缓存只在数据库会话内部共享。
那么,一级缓存的工做流程是怎样的呢?咱们从源码层面来学习一下。
工做流程
一级缓存执行的时序图,以下图所示。
源码分析
接下来将对MyBatis查询相关的核心类和一级缓存的源码进行走读。这对后面学习二级缓存也有帮助。
SqlSession: 对外提供了用户和数据库之间交互须要的全部方法,隐藏了底层的细节。默认实现类是DefaultSqlSession。
Executor: SqlSession向用户提供操做数据库的方法,但和数据库操做有关的职责都会委托给Executor。
以下图所示,Executor有若干个实现类,为Executor赋予了不一样的能力,你们能够根据类名,自行学习每一个类的基本做用。
在一级缓存的源码分析中,主要学习BaseExecutor的内部实现。
BaseExecutor: BaseExecutor是一个实现了Executor接口的抽象类,定义若干抽象方法,在执行的时候,把具体的操做委托给子类进行执行。
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;
在一级缓存的介绍中提到对Local Cache的查询和写入是在Executor内部完成的。在阅读BaseExecutor的代码后发现Local Cache是BaseExecutor内部的一个成员变量,以下代码所示。
public abstract class BaseExecutor implements Executor { protected ConcurrentLinkedQueue<DeferredLoad> deferredLoads; protected PerpetualCache localCache;
Cache: MyBatis中的Cache接口,提供了和缓存相关的最基本的操做,以下图所示。
有若干个实现类,使用装饰器模式互相组装,提供丰富的操控缓存的能力,部分实现类以下图所示。
BaseExecutor成员变量之一的PerpetualCache,是对Cache接口最基本的实现,其实现很是简单,内部持有HashMap,对一级缓存的操做实则是对HashMap的操做。以下代码所示。
public class PerpetualCache implements Cache { private String id; private Map<Object, Object> cache = new HashMap<Object, Object>();
在阅读相关核心类代码后,从源代码层面对一级缓存工做中涉及到的相关代码,出于篇幅的考虑,对源码作适当删减,读者朋友能够结合本文,后续进行更详细的学习。
为执行和数据库的交互,首先须要初始化SqlSession,经过DefaultSqlSessionFactory开启SqlSession:
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) { ............ final Executor executor = configuration.newExecutor(tx, execType); return new DefaultSqlSession(configuration, executor, autoCommit); }
在初始化SqlSesion时,会使用Configuration类建立一个全新的Executor,做为DefaultSqlSession构造函数的参数,建立Executor代码以下所示:
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); } // 尤为能够注意这里,若是二级缓存开关开启的话,是使用CahingExecutor装饰BaseExecutor的子类 if (cacheEnabled) { executor = new CachingExecutor(executor); } executor = (Executor) interceptorChain.pluginAll(executor); return executor; }
SqlSession建立完毕后,根据Statment的不一样类型,会进入SqlSession的不一样方法中,若是是Select语句的话,最后会执行到SqlSession的selectList,代码以下所示:
@Override public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) { MappedStatement ms = configuration.getMappedStatement(statement); return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER); }
SqlSession把具体的查询职责委托给了Executor。若是只开启了一级缓存的话,首先会进入BaseExecutor的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); }
在上述代码中,会先根据传入的参数生成CacheKey,进入该方法查看CacheKey是如何生成的,代码以下所示:
CacheKey cacheKey = new CacheKey(); cacheKey.update(ms.getId()); cacheKey.update(rowBounds.getOffset()); cacheKey.update(rowBounds.getLimit()); cacheKey.update(boundSql.getSql()); //后面是update了sql中带的参数 cacheKey.update(value);
在上述的代码中,将MappedStatement的Id、sql的offset、Sql的limit、Sql自己以及Sql中的参数传入了CacheKey这个类,最终构成CacheKey。如下是这个类的内部结构:
private static final int DEFAULT_MULTIPLYER = 37; private static final int DEFAULT_HASHCODE = 17; private int multiplier; private int hashcode; private long checksum; private int count; private List<Object> updateList; public CacheKey() { this.hashcode = DEFAULT_HASHCODE; this.multiplier = DEFAULT_MULTIPLYER; this.count = 0; this.updateList = new ArrayList<Object>(); }
首先是成员变量和构造函数,有一个初始的hachcode和乘数,同时维护了一个内部的updatelist。在CacheKey的update方法中,会进行一个hashcode和checksum的计算,同时把传入的参数添加进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); }
同时重写了CacheKey的equals方法,代码以下所示:
@Override public boolean equals(Object object) { ............. 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; }
除去hashcode,checksum和count的比较外,只要updatelist中的元素一一对应相等,那么就能够认为是CacheKey相等。只要两条SQL的下列五个值相同,便可以认为是相同的SQL。
Statement Id + Offset + Limmit + Sql + Params
BaseExecutor的query方法继续往下走,代码以下所示:
list = resultHandler == null ? (List<E>) localCache.getObject(key) : null; if (list != null) { // 这个主要是处理存储过程用的。 handleLocallyCachedOutputParameters(ms, key, parameter, boundSql); } else { list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql); }
若是查不到的话,就从数据库查,在queryFromDatabase中,会对localcache进行写入。
在query方法执行的最后,会判断一级缓存级别是不是STATEMENT级别,若是是的话,就清空缓存,这也就是STATEMENT级别的一级缓存没法共享localCache的缘由。代码以下所示:
if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) { clearLocalCache(); }
在源码分析的最后,咱们确认一下,若是是insert/delete/update方法,缓存就会刷新的缘由。
SqlSession的insert方法和delete方法,都会统一走update的流程,代码以下所示:
@Override public int insert(String statement, Object parameter) { return update(statement, parameter); } @Override public int delete(String statement) { return update(statement, null); }
update方法也是委托给了Executor执行。BaseExecutor的执行方法以下所示。
@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); }
每次执行update前都会清空localCache。
至此,一级缓存的工做流程讲解以及源码分析完毕。
在上文中提到的一级缓存中,其最大的共享范围就是一个SqlSession内部,若是多个SqlSession之间须要共享缓存,则须要使用到二级缓存。开启二级缓存后,会使用CachingExecutor装饰Executor,进入一级缓存的查询流程前,先在CachingExecutor进行二级缓存的查询,具体的工做流程以下所示。
二级缓存开启后,同一个namespace下的全部操做语句,都影响着同一个Cache,即二级缓存被多个SqlSession共享,是一个全局的变量。
当开启缓存后,数据的查询执行的流程就是 二级缓存 -> 一级缓存 -> 数据库。
要正确的使用二级缓存,需完成以下配置的。
<setting name="cacheEnabled" value="true"/>
cache标签用于声明这个namespace使用二级缓存,而且能够自定义配置。
<cache/>
cache-ref表明引用别的命名空间的Cache配置,两个命名空间的操做使用的是同一个Cache。
<cache-ref namespace="mapper.StudentMapper"/>
接下来咱们经过实验,了解MyBatis二级缓存在使用上的一些特色。
在本实验中,id为1的学生名称初始化为点点。
实验1
测试二级缓存效果,不提交事务,sqlSession1查询完数据后,sqlSession2相同的查询是否会从缓存中获取数据。
@Test public void testCacheWithoutCommitOrClose() throws Exception { SqlSession sqlSession1 = factory.openSession(true); SqlSession sqlSession2 = factory.openSession(true); StudentMapper studentMapper = sqlSession1.getMapper(StudentMapper.class); StudentMapper studentMapper2 = sqlSession2.getMapper(StudentMapper.class); System.out.println("studentMapper读取数据: " + studentMapper.getStudentById(1)); System.out.println("studentMapper2读取数据: " + studentMapper2.getStudentById(1)); }
执行结果:
咱们能够看到,当sqlsession没有调用commit()方法时,二级缓存并无起到做用。
实验2
测试二级缓存效果,当提交事务时,sqlSession1查询完数据后,sqlSession2相同的查询是否会从缓存中获取数据。
@Test public void testCacheWithCommitOrClose() throws Exception { SqlSession sqlSession1 = factory.openSession(true); SqlSession sqlSession2 = factory.openSession(true); StudentMapper studentMapper = sqlSession1.getMapper(StudentMapper.class); StudentMapper studentMapper2 = sqlSession2.getMapper(StudentMapper.class); System.out.println("studentMapper读取数据: " + studentMapper.getStudentById(1)); sqlSession1.commit(); System.out.println("studentMapper2读取数据: " + studentMapper2.getStudentById(1)); }
从图上可知,sqlsession2的查询,使用了缓存,缓存的命中率是0.5。
实验3
测试update操做是否会刷新该namespace下的二级缓存。
@Test public void testCacheWithUpdate() throws Exception { SqlSession sqlSession1 = factory.openSession(true); SqlSession sqlSession2 = factory.openSession(true); SqlSession sqlSession3 = factory.openSession(true); StudentMapper studentMapper = sqlSession1.getMapper(StudentMapper.class); StudentMapper studentMapper2 = sqlSession2.getMapper(StudentMapper.class); StudentMapper studentMapper3 = sqlSession3.getMapper(StudentMapper.class); System.out.println("studentMapper读取数据: " + studentMapper.getStudentById(1)); sqlSession1.commit(); System.out.println("studentMapper2读取数据: " + studentMapper2.getStudentById(1)); studentMapper3.updateStudentName("方方",1); sqlSession3.commit(); System.out.println("studentMapper2读取数据: " + studentMapper2.getStudentById(1)); }
咱们能够看到,在sqlSession3更新数据库,并提交事务后,sqlsession2的StudentMapper namespace下的查询走了数据库,没有走Cache。
实验4
验证MyBatis的二级缓存不适应用于映射文件中存在多表查询的状况。
一般咱们会为每一个单表建立单独的映射文件,因为MyBatis的二级缓存是基于namespace的,多表查询语句所在的namspace没法感应到其余namespace中的语句对多表查询中涉及的表进行的修改,引起脏数据问题。
@Test public void testCacheWithDiffererntNamespace() throws Exception { SqlSession sqlSession1 = factory.openSession(true); SqlSession sqlSession2 = factory.openSession(true); SqlSession sqlSession3 = factory.openSession(true); StudentMapper studentMapper = sqlSession1.getMapper(StudentMapper.class); StudentMapper studentMapper2 = sqlSession2.getMapper(StudentMapper.class); ClassMapper classMapper = sqlSession3.getMapper(ClassMapper.class); System.out.println("studentMapper读取数据: " + studentMapper.getStudentByIdWithClassInfo(1)); sqlSession1.close(); System.out.println("studentMapper2读取数据: " + studentMapper2.getStudentByIdWithClassInfo(1)); classMapper.updateClassName("特点一班",1); sqlSession3.commit(); System.out.println("studentMapper2读取数据: " + studentMapper2.getStudentByIdWithClassInfo(1)); }
执行结果:
在这个实验中,咱们引入了两张新的表,一张class,一张classroom。class中保存了班级的id和班级名,classroom中保存了班级id和学生id。咱们在StudentMapper中增长了一个查询方法getStudentByIdWithClassInfo,用于查询学生所在的班级,涉及到多表查询。在ClassMapper中添加了updateClassName,根据班级id更新班级名的操做。
当sqlsession1的studentmapper查询数据后,二级缓存生效。保存在StudentMapper的namespace下的cache中。当sqlSession3的classMapper的updateClassName方法对class表进行更新时,updateClassName不属于StudentMapper的namespace,因此StudentMapper下的cache没有感应到变化,没有刷新缓存。当StudentMapper中一样的查询再次发起时,从缓存中读取了脏数据。
实验5
为了解决实验4的问题呢,可使用Cache ref,让ClassMapper引用StudenMapper命名空间,这样两个映射文件对应的Sql操做都使用的是同一块缓存了。
执行结果:
不过这样作的后果是,缓存的粒度变粗了,多个Mapper namespace下的全部操做都会对缓存使用形成影响。
MyBatis二级缓存的工做流程和前文提到的一级缓存相似,只是在一级缓存处理前,用CachingExecutor装饰了BaseExecutor的子类,在委托具体职责给delegate以前,实现了二级缓存的查询和写入功能,具体类关系图以下图所示。
源码分析
源码分析从CachingExecutor的query方法展开,源代码走读过程当中涉及到的知识点较多,不能一一详细讲解,读者朋友能够自行查询相关资料来学习。
CachingExecutor的query方法,首先会从MappedStatement中得到在配置初始化时赋予的Cache。
Cache cache = ms.getCache();
本质上是装饰器模式的使用,具体的装饰链是
SynchronizedCache -> LoggingCache -> SerializedCache -> LruCache -> PerpetualCache。
如下是具体这些Cache实现类的介绍,他们的组合为Cache赋予了不一样的能力。
而后是判断是否须要刷新缓存,代码以下所示:
flushCacheIfRequired(ms);
在默认的设置中SELECT语句不会刷新缓存,insert/update/delte会刷新缓存。进入该方法。代码以下所示:
private void flushCacheIfRequired(MappedStatement ms) { Cache cache = ms.getCache(); if (cache != null && ms.isFlushCacheRequired()) { tcm.clear(cache); } }
MyBatis的CachingExecutor持有了TransactionalCacheManager,即上述代码中的tcm。
TransactionalCacheManager中持有了一个Map,代码以下所示:
private Map<Cache, TransactionalCache> transactionalCaches = new HashMap<Cache, TransactionalCache>();
这个Map保存了Cache和用TransactionalCache包装后的Cache的映射关系。
TransactionalCache实现了Cache接口,CachingExecutor会默认使用他包装初始生成的Cache,做用是若是事务提交,对缓存的操做才会生效,若是事务回滚或者不提交事务,则不对缓存产生影响。
在TransactionalCache的clear,有如下两句。清空了须要在提交时加入缓存的列表,同时设定提交时清空缓存,代码以下所示:
@Override public void clear() { clearOnCommit = true; entriesToAddOnCommit.clear(); }
CachingExecutor继续往下走,ensureNoOutParams主要是用来处理存储过程的,暂时不用考虑。
if (ms.isUseCache() && resultHandler == null) { ensureNoOutParams(ms, parameterObject, boundSql);
以后会尝试从tcm中获取缓存的列表。
List<E> list = (List<E>) tcm.getObject(cache, key);
在getObject方法中,会把获取值的职责一路传递,最终到PerpetualCache。若是没有查到,会把key加入Miss集合,这个主要是为了统计命中率。
Object object = delegate.getObject(key); if (object == null) { entriesMissedInCache.add(key); }
CachingExecutor继续往下走,若是查询到数据,则调用tcm.putObject方法,往缓存中放入值。
if (list == null) { list = delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql); tcm.putObject(cache, key, list); // issue #578 and #116 }
tcm的put方法也不是直接操做缓存,只是在把此次的数据和key放入待提交的Map中。
@Override public void putObject(Object key, Object object) { entriesToAddOnCommit.put(key, object); }
从以上的代码分析中,咱们能够明白,若是不调用commit方法的话,因为TranscationalCache的做用,并不会对二级缓存形成直接的影响。所以咱们看看Sqlsession的commit方法中作了什么。代码以下所示:
@Override public void commit(boolean force) { try { executor.commit(isCommitOrRollbackRequired(force));
由于咱们使用了CachingExecutor,首先会进入CachingExecutor实现的commit方法。
@Override public void commit(boolean required) throws SQLException { delegate.commit(required); tcm.commit(); }
会把具体commit的职责委托给包装的Executor。主要是看下tcm.commit(),tcm最终又会调用到TrancationalCache。
public void commit() { if (clearOnCommit) { delegate.clear(); } flushPendingEntries(); reset(); }
看到这里的clearOnCommit就想起刚才TrancationalCache的clear方法设置的标志位,真正的清理Cache是放到这里来进行的。具体清理的职责委托给了包装的Cache类。以后进入flushPendingEntries方法。代码以下所示:
private void flushPendingEntries() { for (Map.Entry<Object, Object> entry : entriesToAddOnCommit.entrySet()) { delegate.putObject(entry.getKey(), entry.getValue()); } ................ }
在flushPendingEntries中,将待提交的Map进行循环处理,委托给包装的Cache类,进行putObject的操做。
后续的查询操做会重复执行这套流程。若是是insert|update|delete的话,会统一进入CachingExecutor的update方法,其中调用了这个函数,代码以下所示:
private void flushCacheIfRequired(MappedStatement ms)
在二级缓存执行流程后就会进入一级缓存的执行流程,所以再也不赘述。
本文对介绍了MyBatis一二级缓存的基本概念,并从应用及源码的角度对MyBatis的缓存机制进行了分析。最后对MyBatis缓存机制作了必定的总结,我的建议MyBatis缓存特性在生产环境中进行关闭,单纯做为一个ORM框架使用可能更为合适。
凯伦,美团点评后端研发工程师,2016年毕业于上海海事大学,现从事美团点评餐饮平台相关的开发工做。公众号ID: KailunTalk,欢迎关注,一块儿探讨更多技术知识。