基于我的的兴趣,为你们分享Mybatis的一级缓存以及二级缓存的特性。java
本次分析中涉及到的代码和数据库表均放在Github上,地址: mybatis-cache-demo。git
为达到以上三个目的,本文按照如下顺序展开。github
本章节会对Mybatis进行大致的介绍,分为官方定义和核心组件介绍。
首先是Mybatis官方定义,以下所示。算法
MyBatis是支持定制化SQL、存储过程以及高级映射的优秀的持久层框架。MyBatis避免了几乎全部的JDBC代码和手动设置参数以及获取结果集。MyBatis能够对配置和原生Map使用简单的XML或注解,将接口和Java 的POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。sql
其次是Mybatis的几个核心概念。数据库
下图就是一个针对Student表操做的接口文件StudentMapper,在StudentMapper中,咱们能够若干方法,这个方法背后就是表明着要执行的Sql的意义。
缓存
在Mybatis初始化的时候,每个语句都会使用对应的MappedStatement表明,使用namespace+语句自己的id来表明这个语句。以下代码所示,使用mapper.StudentMapper.getStudentById表明其对应的Sql。安全
SELECT id,name,age FROM student WHERE id = #{id}复制代码
在Mybatis执行时,会进入对应接口的方法,经过类名加上方法名的组合生成id,找到须要的MappedStatement,交给执行器使用。
至此,Mybatis的基础概念介绍完毕。bash
在系统代码的运行中,咱们可能会在一个数据库会话中,执行屡次查询条件彻底相同的Sql,鉴于平常应用的大部分场景都是读多写少,这重复的查询会带来必定的网络开销,同时select查询的量比较大的话,对数据库的性能是有比较大的影响的。网络
若是是Mysql数据库的话,在服务端和Jdbc端都开启预编译支持的话,能够在本地JVM端缓存Statement,能够在Mysql服务端直接执行Sql,省去编译Sql的步骤,但也没法避免和数据库之间的重复交互。关于Jdbc和Mysql预编译缓存的事情,能够看个人这篇博客JDBC和Mysql那些事。
Mybatis提供了一级缓存的方案来优化在数据库会话间重复查询的问题。实现的方式是每个SqlSession中都持有了本身的缓存,一种是SESSION级别,即在一个Mybatis会话中执行的全部语句,都会共享这一个缓存。一种是STATEMENT级别,能够理解为缓存只对当前执行的这一个statement有效。若是用一张图来表明一级查询的查询过程的话,能够用下图表示。
上文介绍了一级缓存的实现方式,解决了什么问题。在这个章节,咱们学习如何使用Mybatis的一级缓存。只须要在Mybatis的配置文件中,添加以下语句,就可使用一级缓存。共有两个选项,SESSION或者STATEMENT,默认是SESSION级别。
<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的学生名称是凯伦。
开启一级缓存,范围为会话级别,调用三次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));
}复制代码
执行结果:
在此次的试验中,咱们增长了对数据库的修改操做,验证在一次数据库会话中,对数据库发生了修改操做,一级缓存是否会失效。
@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();
}复制代码
执行结果:
开启两个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));
}复制代码
这一章节主要从一级缓存的工做流程和源码层面对一级缓存进行学习。
根据一级缓存的工做流程,咱们绘制出一级缓存执行的时序图,以下图所示。
4.1 去数据库中查询数据,获得查询结果;
4.2 将key和查询到的结果做为key和value,放入Local Cache中。
4.3. 将查询结果返回;复制代码
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就是它内部的一个成员变量,以下代码所示。public abstract class BaseExecutor implements Executor {
protected ConcurrentLinkedQueue<DeferredLoad> deferredLoads;
protected PerpetualCache localCache;复制代码
Cache: Mybatis中的Cache接口,提供了和缓存相关的最基本的操做,有若干个实现类,使用装饰器模式互相组装,提供丰富的操控缓存的能力。public class PerpetualCache implements Cache {
private String id;
private Map<Object, Object> cache = new HashMap<Object, Object>();复制代码
在阅读相关核心类代码后,从源代码层面对一级缓存工做中涉及到的相关代码,出于篇幅的考虑,对源码作适当删减,读者朋友能够结合本文,后续进行更详细的学习。
为了执行和数据库的交互,首先会经过DefaultSqlSessionFactory开启一个SqlSession,在建立SqlSession的过程当中,会经过Configuration类建立一个全新的Executor,做为DefaultSqlSession构造函数的参数,代码以下所示。
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
............
final Executor executor = configuration.newExecutor(tx, execType);
return new DefaultSqlSession(configuration, executor, autoCommit);
}复制代码
若是用户不进行制定的话,Configuration在建立Executor时,默认建立的类型就是SimpleExecutor,它是一个简单的执行类,只是单纯执行Sql。如下是具体用来建立的代码。
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相等的呢,在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进行二级缓存的查询,具体的工做流程以下所示。
要正确的使用二级缓存,需完成以下配置的。
1 在Mybatis的配置文件中开启二级缓存。
<setting name="cacheEnabled" value="true"/>复制代码
2 在Mybatis的映射XML中配置cache或者 cache-ref 。
<cache/>复制代码
cache标签用于声明这个namespace使用二级缓存,而且能够自定义配置。
<cache-ref namespace="mapper.StudentMapper"/>复制代码
cache-ref表明引用别的命名空间的Cache配置,两个命名空间的操做使用的是同一个Cache。
在本章节,经过实验,了解Mybatis二级缓存在使用上的一些特色。
在本实验中,id为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));
}复制代码
执行结果:
测试二级缓存效果,当提交事务时,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));
}复制代码
测试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));
}复制代码
验证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));
}复制代码
执行结果:
为了解决实验4的问题呢,可使用Cache ref,让ClassMapper引用StudenMapper命名空间,这样两个映射文件对应的Sql操做都使用的是同一块缓存了。
执行结果:
Mybatis二级缓存的工做流程和前文提到的一级缓存相似,只是在一级缓存处理前,用CachingExecutor装饰了BaseExecutor的子类,实现了缓存的查询和写入功能,因此二级缓存直接从源码开始分析。
源码分析从CachingExecutor的query方法展开,源代码走读过程当中涉及到的知识点较多,不能一一详细讲解,能够在文后留言,我会在交流环节更详细的表示出来。
CachingExecutor的query方法,首先会从MappedStatement中得到在配置初始化时赋予的cache。
Cache cache = ms.getCache();复制代码
本质上是装饰器模式的使用,具体的执行链是
SynchronizedCache -> LoggingCache -> SerializedCache -> LruCache -> PerpetualCache。
而后是判断是否须要刷新缓存,代码以下所示。
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)复制代码