主题

  之前学习了一下MyBatis的一级缓存,主要涉及到BaseExecutor这个类. 现在准备学习记录下MyBatis二级缓存.

配置二级缓存与初始化发生的事情

首先二级缓存默认是不开启的,需要自己配置开启.

如上图,需要在configuration里去开启.

其次在需要用到二级缓存的Mapper的配置里做一些操作,如下图,增加一个cache节点

至此就可以在UserMapper上开启二级缓存了.

当MaBatis初始化的时候,需要解析各种XML配置来生成SQLSessionFactory,解析Mapper的配置也是其中一环.而解析Mapper的配置中,解析Cache节点又是其中的一部分.

这个解析cache会做什么事情呢?

如上图所示,会往builderAssistant里去新建一个Cache对象(其中的参数是你之前XML里配置的).

Cache类的设计也是装饰着模式,层层嵌套.比如我们new出来的Cache中会包裹一个打印缓存命中信息的LoggingCache,我们指定的LruCache包裹着PerpetualCache(一级缓存也使用这个Cache)等等.

MapperBuilderAssistant是个Builder模式,解析Mapper的最后会调用assistant的addMappedStatement方法.

     public MappedStatement addMappedStatement(
String id,
SqlSource sqlSource,
StatementType statementType,
SqlCommandType sqlCommandType,
Integer fetchSize,
Integer timeout,
String parameterMap,
Class<?> parameterType,
String resultMap,
Class<?> resultType,
ResultSetType resultSetType,
boolean flushCache,
boolean useCache,
boolean resultOrdered,
KeyGenerator keyGenerator,
String keyProperty,
String keyColumn,
String databaseId,
LanguageDriver lang,
String resultSets) { if (unresolvedCacheRef) {
throw new IncompleteElementException("Cache-ref not yet resolved");
} id = applyCurrentNamespace(id, false);
boolean isSelect = sqlCommandType == SqlCommandType.SELECT; MappedStatement.Builder statementBuilder = new MappedStatement.Builder(configuration, id, sqlSource, sqlCommandType)
.resource(resource)
.fetchSize(fetchSize)
.timeout(timeout)
.statementType(statementType)
.keyGenerator(keyGenerator)
.keyProperty(keyProperty)
.keyColumn(keyColumn)
.databaseId(databaseId)
.lang(lang)
.resultOrdered(resultOrdered)
.resultSets(resultSets)
.resultMaps(getStatementResultMaps(resultMap, resultType, id))
.resultSetType(resultSetType)
.flushCacheRequired(valueOrDefault(flushCache, !isSelect))
.useCache(valueOrDefault(useCache, isSelect))
.cache(currentCache); ParameterMap statementParameterMap = getStatementParameterMap(parameterMap, parameterType, id);
if (statementParameterMap != null) {
statementBuilder.parameterMap(statementParameterMap);
} MappedStatement statement = statementBuilder.build();
configuration.addMappedStatement(statement);
return statement;
}

把刚才new出来的cache设置到MappedStatement.Builder中,最后build出一个MappedStatement,并添加到Configuration里. 如下图

所以其实我们刚才在Mapper的XML里配置的cache,最后生成对应的java Cache对象,是放在MappedStatement里的,而MappedStatement是什么东西? 看了如下3个截图大家应该就明白了.就是你Mapper XML里配置的一个一个DML对应的节点,当然1个Mapper.XML里会有很多这样的节点,而他们是公用1个Cache的.

MappedStatement是全局唯一的对象,被放到了Configuration里,不同的Executor需要用到的时候都会从Configuration里去找SQL对应的MappedStatement.(其实是SqlSession调用Executor的query方法的时候会去根据类.方法名在configuration里查找mappedStatement并传入)

CachingExecutor

正如之前文章记录的那样,CachingExecutor是包裹在BaseExecutor外的一层Executor,使用的是装饰着模式. 二级缓存主要是在它里面实现的.

先来看一个Demo

2018-10-14 12:04:17,138 DEBUG [main] logging.LogFactory : Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Cache Hit Ratio [test.mapper.UserMapper]: 0.0
Opening JDBC Connection
Sun Oct 14 12:04:17 CST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Created connection 25300561.
Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@1820e51]
==> Preparing: select id, user_id, user_name, real_name, email, creator_uid, modifier_uid, created_at, updated_at, del from user where id = ?
==> Parameters: 1(Integer)
<== Columns: id, user_id, user_name, real_name, email, creator_uid, modifier_uid, created_at, updated_at, del
<== Row: 1, 1, test, realName, jyzjyz12@163.com, 1, 1, 2018-09-24 10:10:43.0, 2018-09-24 10:10:46.0, 0
<== Total: 1
User{id=1, userId=1, userName='test', realName='realName', email='jyzjyz12@163.com', creatorUid=1, modifierUid=1, createdAt=Mon Sep 24 10:10:43 CST 2018, updatedAt=Mon Sep 24 10:10:46 CST 2018, del=false}
Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@1820e51]
Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@1820e51]
Returned connection 25300561 to pool.
Cache Hit Ratio [test.mapper.UserMapper]: 0.5
User{id=1, userId=1, userName='test', realName='realName', email='jyzjyz12@163.com', creatorUid=1, modifierUid=1, createdAt=Mon Sep 24 10:10:43 CST 2018, updatedAt=Mon Sep 24 10:10:46 CST 2018, del=false}

如上图,从1个SQLSessionFactory里获取了2个SqlSession,分别调用了1次selectByPrimaryKey.

而红色部分输出看到 第一个sqlSession打印了1次SQL, 第二次调用selectByPrimaryKey的时候会打印蓝色的部分,输出缓存命中,概率为1/2,然后没有打印红色的查询语句,而是直接输出返回打印了之前缓存中的对象.

CachingExecutor的query方法如下图

与BaseExecutor的处理方法大致类似,只是先会从MapperedStatement里去寻找是否配置过缓存,有的话就从TransactionalCacheManager中通过Cache做为Key去找TransactionalCache,再从TransactionalCache中根据CacheKey查找结果, TransactionalCache也是Cache的一种实现,目的是为了支持事务回滚提交操作.

TransactionalCache中缓存对象的key为CacheKey,CacheKey之前在一级缓存中已经分享过,value为数据库查询结果,即一个ArrayList.

如果缓存中没有,那就委托内部wrapped的对象,也就是SImpleExecutor去调用query去数据库中找.

小结

总结一下二级缓存如何实现:

1.初始化阶段初始化Cache设置到MappedStatement里,MappedStatement设置到Configuration里.

2.执行查询的时候SqlSession去Configuration里找到MappedStatement传给CachingExecutor.

3.CachingExecutor获取MappedStatement再获取其中的Cache,根据Cache是否null,判断是否有开启二级缓存.

4.如果有开启,那Cache不为null,去TransactionalCacheManager中根据Cache为Key找到TransactionalCache,为null就委托SImpleExecutor继续查数据库.不为null,就在TransactionalCache根据CacheKey找到对应的Value并返回.

MyBatis 学习记录5 MyBatis的二级缓存的更多相关文章

  1. MyBatis 学习记录4 MyBatis的一级缓存

    主题 分享记录一下MyBatis的一级缓存相关的学习. Demo public static void firstLevelCache() { init("mybatis-config.xm ...

  2. mybatis学习记录二——mybatis开发dao的方法

    4.1     SqlSession使用范围 4.1.1     SqlSessionFactoryBuilder 通过SqlSessionFactoryBuilder创建会话工厂SqlSession ...

  3. 【MyBatis学习13】MyBatis中的二级缓存

    1. 二级缓存的原理 前面介绍了,mybatis中的二级缓存是mapper级别的缓存,值得注意的是,不同的mapper都有一个二级缓存,也就是说,不同的mapper之间的二级缓存是互不影响的.为了更加 ...

  4. MyBatis学习总结(七)——Mybatis缓存(转载)

      孤傲苍狼 只为成功找方法,不为失败找借口! MyBatis学习总结(七)--Mybatis缓存 一.MyBatis缓存介绍 正如大多数持久层框架一样,MyBatis 同样提供了一级缓存和二级缓存的 ...

  5. 【转】MyBatis学习总结(七)——Mybatis缓存

    [转]MyBatis学习总结(七)——Mybatis缓存 一.MyBatis缓存介绍 正如大多数持久层框架一样,MyBatis 同样提供了一级缓存和二级缓存的支持 一级缓存: 基于PerpetualC ...

  6. 【转】MyBatis学习总结(一)——MyBatis快速入门

    [转]MyBatis学习总结(一)——MyBatis快速入门 一.Mybatis介绍 MyBatis是一个支持普通SQL查询,存储过程和高级映射的优秀持久层框架.MyBatis消除了几乎所有的JDBC ...

  7. 转:MyBatis学习总结(Mybatis总结精华文章)

    http://www.cnblogs.com/xdp-gacl/tag/MyBatis%E5%AD%A6%E4%B9%A0%E6%80%BB%E7%BB%93/ 当前标签: MyBatis学习总结   ...

  8. Mybatis学习(五)————— 延迟加载和缓存机制(一级二级缓存)

    一.延迟加载 延迟加载就是懒加载,先去查询主表信息,如果用到从表的数据的话,再去查询从表的信息,也就是如果没用到从表的数据的话,就不查询从表的信息.所以这就是突出了懒这个特点.真是懒啊. Mybati ...

  9. Mybatis学习记录(七)----Mybatis查询缓存

    1. 什么是查询缓存 mybatis提供查询缓存,用于减轻数据压力,提高数据库性能. mybaits提供一级缓存,和二级缓存. 一级缓存是SqlSession级别的缓存.在操作数据库时需要构造 sql ...

随机推荐

  1. save the transient instance before flushing错误解决办法 【待完善】

    近日在项目中遇到以下错误,着实郁闷了一把: org.hibernate.TransientObjectException: object references an unsaved transient ...

  2. BZOJ4518 Sdoi2016 征途 【斜率优化DP】 *

    BZOJ4518 Sdoi2016 征途 Description Pine开始了从S地到T地的征途. 从S地到T地的路可以划分成n段,相邻两段路的分界点设有休息站. Pine计划用m天到达T地.除第m ...

  3. Visual->UIElement->FrameworkElement,带来更多功能的同时也带来了更多的限制

    在 WPF 或 UWP 中,我们平时开发所遇到的那些 UI 控件或组件,都直接或间接继承自 Framework.例如:Grid.StackPanel.Canvas.Border.Image.Butto ...

  4. 使用distillery 实现版本的动态升级&& 动态降级

    备注: distillery  使用很棒的elixir 打包构建工具,下面演示的是升级以及降级   1. 参考项目 https://github.com/rongfengliang/phoenix-r ...

  5. VLOOKUP函数使用

    跟财务老婆学习了个excel函数 -- vlookup函数,记录一下,省得下次用忘了. 需求:有两张表,将第一张表的第二个字段g2去搜索第二张表的字段d2,如果相等,将第二张表的第三个字段追加到第一张 ...

  6. ffmpeg从USB摄像头采集一张原始图片(转)

    本文讲解使用ffmpeg从USB摄像头中采集一帧数据并写入文件保存,测试平台使用全志A20平台,其他平台修改交叉工具链即可移植.开发环境使用eclipse+CDT.交叉工具链使用arm-Linux-g ...

  7. bzoj 3994 [SDOI2015]约数个数和——反演

    题目:https://www.lydsy.com/JudgeOnline/problem.php?id=3994 \( d(i*j)=\sum\limits_{x|i}\sum\limits_{y|j ...

  8. U盘永久系统-centos

    U盘永久系统-centos 问题: 服务器centos系统崩溃,重装需要备份其中数据,约4T,实验室有远程存储服务器,然而rescue模式进去后无法挂载远程存储,只好做一个真正的U盘系统解决了. 方案 ...

  9. 在Google的GKE上创建支持Internal Load Balancer的Service

    在Google的Kubernetes Engine上发布service,可以采用除On-Promise相同的Cluster IP和NodePort两种方式外,还可以创建LoadBalaner的Serv ...

  10. js的delegate回调例子

    暂时没发现有具体的实际用处,先记录下 <!DOCTYPE html> <html> <head lang="en"> <meta char ...