【MyBatis】MyBatis 二级缓存全详解

x33g5p2x  于2022-05-16 转载在 其他  
字(13.9k)|赞(0)|评价(0)|浏览(513)

1.概述

转载:MyBatis 二级缓存全详解

上一篇文章中我们介绍到了 MyBatis 一级缓存其实就是 SqlSession 级别的缓存,什么是 SqlSession 级别的缓存呢?一级缓存的本质是什么呢? 以及一级缓存失效的原因?我希望你在看下文之前能够回想起来这些内容。

MyBatis 一级缓存最大的共享范围就是一个SqlSession内部,那么如果多个 SqlSession 需要共享缓存,则需要开启二级缓存,开启二级缓存后,会使用 CachingExecutor 装饰 Executor,进入一级缓存的查询流程前,先在CachingExecutor 进行二级缓存的查询,具体的工作流程如下所示

当二级缓存开启后,同一个命名空间(namespace) 所有的操作语句,都影响着一个共同的 cache,也就是二级缓存被多个 SqlSession 共享,是一个全局的变量。当开启缓存后,数据的查询执行的流程就是 二级缓存 -> 一级缓存 -> 数据库。

2.二级缓存开启条件

二级缓存默认是不开启的,需要手动开启二级缓存,实现二级缓存的时候,MyBatis要求返回的POJO必须是可序列化的。开启二级缓存的条件也是比较简单,通过直接在 MyBatis 配置文件中通过

  1. <settings>
  2. <setting name = "cacheEnabled" value = "true" />
  3. </settings>

来开启二级缓存,还需要在 Mapper 的xml 配置文件中加入 <cache> 标签

设置 cache 标签的属性

cache 标签有多个属性,一起来看一些这些属性分别代表什么意义

eviction: 缓存回收策略,有这几种回收策略

  • LRU - 最近最少回收,移除最长时间不被使用的对象
  • FIFO - 先进先出,按照缓存进入的顺序来移除它们
  • SOFT - 软引用,移除基于垃圾回收器状态和软引用规则的对象
  • WEAK - 弱引用,更积极的移除基于垃圾收集器和弱引用规则的对象

默认是 LRU 最近最少回收策略

  • flushinterval 缓存刷新间隔,缓存多长时间刷新一次,默认不清空,设置一个毫秒值
  • readOnly: 是否只读;true 只读,MyBatis 认为所有从缓存中获取数据的操作都是只读操作,不会修改数据。MyBatis 为了加快获取数据,直接就会将数据在缓存中的引用交给用户。不安全,速度快。读写(默认):MyBatis 觉得数据可能会被修改
  • size : 缓存存放多少个元素
  • type: 指定自定义缓存的全类名(实现Cache 接口即可)
  • blocking: 若缓存中找不到对应的key,是否会一直blocking,直到有对应的数据进入缓存。

3.探究二级缓存

我们继续以 MyBatis 一级缓存文章中的例子为基础,搭建一个满足二级缓存的例子,来对二级缓存进行探究,例子如下(对 一级缓存的例子部分源码进行修改):

Dept.java

  1. //存放在共享缓存中数据进行序列化操作和反序列化操作
  2. //因此数据对应实体类必须实现【序列化接口】
  3. public class Dept implements Serializable {
  4. private Integer deptNo;
  5. private String dname;
  6. private String loc;
  7. public Dept() {}
  8. public Dept(Integer deptNo, String dname, String loc) {
  9. this.deptNo = deptNo;
  10. this.dname = dname;
  11. this.loc = loc;
  12. }
  13. get and set...
  14. @Override
  15. public String toString() {
  16. return "Dept{" +
  17. "deptNo=" + deptNo +
  18. ", dname='" + dname + '\'' +
  19. ", loc='" + loc + '\'' +
  20. '}';
  21. }
  22. }

myBatis-config.xml

在myBatis-config 中添加开启二级缓存的条件

  1. <!-- 通知 MyBatis 框架开启二级缓存 -->
  2. <settings>
  3. <setting name="cacheEnabled" value="true"/>
  4. </settings>

DeptDao.xml

还需要在 Mapper 对应的xml中添加 cache 标签,表示对哪个mapper 开启缓存

  1. <!-- 表示DEPT表查询结果保存到二级缓存(共享缓存) -->
  2. <cache/>

对应的二级缓存测试类如下:

  1. public class MyBatisSecondCacheTest {
  2. private SqlSession sqlSession;
  3. SqlSessionFactory factory;
  4. @Before
  5. public void start() throws IOException {
  6. InputStream is = Resources.getResourceAsStream("myBatis-config.xml");
  7. SqlSessionFactoryBuilder builderObj = new SqlSessionFactoryBuilder();
  8. factory = builderObj.build(is);
  9. sqlSession = factory.openSession();
  10. }
  11. @After
  12. public void destory(){
  13. if(sqlSession!=null){
  14. sqlSession.close();
  15. }
  16. }
  17. @Test
  18. public void testSecondCache(){
  19. //会话过程中第一次发送请求,从数据库中得到结果
  20. //得到结果之后,mybatis自动将这个查询结果放入到当前用户的一级缓存
  21. DeptDao dao = sqlSession.getMapper(DeptDao.class);
  22. Dept dept = dao.findByDeptNo(1);
  23. System.out.println("第一次查询得到部门对象 = "+dept);
  24. //触发MyBatis框架从当前一级缓存中将Dept对象保存到二级缓存
  25. sqlSession.commit();
  26. // 改成 sqlSession.close(); 效果相同
  27. SqlSession session2 = factory.openSession();
  28. DeptDao dao2 = session2.getMapper(DeptDao.class);
  29. Dept dept2 = dao2.findByDeptNo(1);
  30. System.out.println("第二次查询得到部门对象 = "+dept2);
  31. }
  32. }

测试二级缓存效果,提交事务,sqlSession查询完数据后,sqlSession2相同的查询是否会从缓存中获取数据。

通过结果可以得知,首次执行的SQL语句是从数据库中查询得到的结果,然后第一个 SqlSession 执行提交,第二个 SqlSession 执行相同的查询后是从缓存中查取的。

用一下这幅图能够比较直观的反映两次 SqlSession 的缓存命中

4.二级缓存失效的条件

与一级缓存一样,二级缓存也会存在失效的条件的,下面我们就来探究一下哪些情况会造成二级缓存失效

4.1 第一次SqlSession 未提交

SqlSession 在未提交的时候,SQL 语句产生的查询结果还没有放入二级缓存中,这个时候 SqlSession2 在查询的时候是感受不到二级缓存的存在的,修改对应的测试类,结果如下:

  1. @Test
  2. public void testSqlSessionUnCommit(){
  3. //会话过程中第一次发送请求,从数据库中得到结果
  4. //得到结果之后,mybatis自动将这个查询结果放入到当前用户的一级缓存
  5. DeptDao dao = sqlSession.getMapper(DeptDao.class);
  6. Dept dept = dao.findByDeptNo(1);
  7. System.out.println("第一次查询得到部门对象 = "+dept);
  8. //触发MyBatis框架从当前一级缓存中将Dept对象保存到二级缓存
  9. SqlSession session2 = factory.openSession();
  10. DeptDao dao2 = session2.getMapper(DeptDao.class);
  11. Dept dept2 = dao2.findByDeptNo(1);
  12. System.out.println("第二次查询得到部门对象 = "+dept2);
  13. }

产生的输出结果:

4.2 更新对二级缓存影响

与一级缓存一样,更新操作很可能对二级缓存造成影响,下面用三个 SqlSession来进行模拟,第一个 SqlSession 只是单纯的提交,第二个 SqlSession 用于检验二级缓存所产生的影响,第三个 SqlSession 用于执行更新操作,测试如下:

  1. @Test
  2. public void testSqlSessionUpdate(){
  3. SqlSession sqlSession = factory.openSession();
  4. SqlSession sqlSession2 = factory.openSession();
  5. SqlSession sqlSession3 = factory.openSession();
  6. // 第一个 SqlSession 执行更新操作
  7. DeptDao deptDao = sqlSession.getMapper(DeptDao.class);
  8. Dept dept = deptDao.findByDeptNo(1);
  9. System.out.println("dept = " + dept);
  10. sqlSession.commit();
  11. // 判断第二个 SqlSession 是否从缓存中读取
  12. DeptDao deptDao2 = sqlSession2.getMapper(DeptDao.class);
  13. Dept dept2 = deptDao2.findByDeptNo(1);
  14. System.out.println("dept2 = " + dept2);
  15. // 第三个 SqlSession 执行更新操作
  16. DeptDao deptDao3 = sqlSession3.getMapper(DeptDao.class);
  17. deptDao3.updateDept(new Dept(1,"ali","hz"));
  18. sqlSession3.commit();
  19. // 判断第二个 SqlSession 是否从缓存中读取
  20. dept2 = deptDao2.findByDeptNo(1);
  21. System.out.println("dept2 = " + dept2);
  22. }

对应的输出结果如下

5.探究多表操作对二级缓存的影响

现有这样一个场景,有两个表,部门表dept(deptNo,dname,loc)和 部门数量表deptNum(id,name,num),其中部门表的名称和部门数量表的名称相同,通过名称能够联查两个表可以知道其坐标(loc)和数量(num),现在我要对部门数量表的 num 进行更新,然后我再次关联dept 和 deptNum 进行查询,你认为这个 SQL 语句能够查询到的 num 的数量是多少?来看一下代码探究一下

DeptNum.java

  1. public class DeptNum {
  2. private int id;
  3. private String name;
  4. private int num;
  5. get and set...
  6. }

DeptVo.java

  1. public class DeptVo {
  2. private Integer deptNo;
  3. private String dname;
  4. private String loc;
  5. private Integer num;
  6. public DeptVo(Integer deptNo, String dname, String loc, Integer num) {
  7. this.deptNo = deptNo;
  8. this.dname = dname;
  9. this.loc = loc;
  10. this.num = num;
  11. }
  12. public DeptVo(String dname, Integer num) {
  13. this.dname = dname;
  14. this.num = num;
  15. }
  16. get and set
  17. @Override
  18. public String toString() {
  19. return "DeptVo{" +
  20. "deptNo=" + deptNo +
  21. ", dname='" + dname + '\'' +
  22. ", loc='" + loc + '\'' +
  23. ", num=" + num +
  24. '}';
  25. }
  26. }

DeptDao.java

  1. public interface DeptDao {
  2. ...
  3. DeptVo selectByDeptVo(String name);
  4. DeptVo selectByDeptVoName(String name);
  5. int updateDeptVoNum(DeptVo deptVo);
  6. }

DeptDao.xml

  1. <select id="selectByDeptVo" resultType="com.mybatis.beans.DeptVo">
  2. select d.deptno,d.dname,d.loc,dn.num from dept d,deptNum dn where dn.name = d.dname
  3. and d.dname = #{name}
  4. </select>
  5. <select id="selectByDeptVoName" resultType="com.mybatis.beans.DeptVo">
  6. select * from deptNum where name = #{name}
  7. </select>
  8. <update id="updateDeptVoNum" parameterType="com.mybatis.beans.DeptVo">
  9. update deptNum set num = #{num} where name = #{dname}
  10. </update>

DeptNum 数据库初始值:

测试类对应如下:

  1. /**
  2. * 探究多表操作对二级缓存的影响
  3. */
  4. @Test
  5. public void testOtherMapper(){
  6. // 第一个mapper 先执行联查操作
  7. SqlSession sqlSession = factory.openSession();
  8. DeptDao deptDao = sqlSession.getMapper(DeptDao.class);
  9. DeptVo deptVo = deptDao.selectByDeptVo("ali");
  10. System.out.println("deptVo = " + deptVo);
  11. // 第二个mapper 执行更新操作 并提交
  12. SqlSession sqlSession2 = factory.openSession();
  13. DeptDao deptDao2 = sqlSession2.getMapper(DeptDao.class);
  14. deptDao2.updateDeptVoNum(new DeptVo("ali",1000));
  15. sqlSession2.commit();
  16. sqlSession2.close();
  17. // 第一个mapper 再次进行查询,观察查询结果
  18. deptVo = deptDao.selectByDeptVo("ali");
  19. System.out.println("deptVo = " + deptVo);
  20. }

测试结果如下:

在对DeptNum 表执行了一次更新后,再次进行联查,发现数据库中查询出的还是 num 为 1050 的值,也就是说,实际上 1050 -> 1000 ,最后一次联查实际上查询的是第一次查询结果的缓存,而不是从数据库中查询得到的值,这样就读到了脏数据。

解决办法

如果是两个mapper命名空间的话,可以使用 <cache-ref>来把一个命名空间指向另外一个命名空间,从而消除上述的影响,再次执行,就可以查询到正确的数据

6.二级缓存源码解析

源码模块主要分为两个部分:二级缓存的创建和二级缓存的使用,首先先对二级缓存的创建进行分析:

6.1 二级缓存的创建

二级缓存的创建是使用 Resource 读取 XML 配置文件开始的

  1. InputStream is = Resources.getResourceAsStream("myBatis-config.xml");
  2. SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
  3. factory = builder.build(is);

读取配置文件后,需要对XML创建 Configuration并初始化

  1. XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
  2. return build(parser.parse());

调用 parser.parse() 解析根目录 /configuration 下面的标签,依次进行解析

  1. public Configuration parse() {
  2. if (parsed) {
  3. throw new BuilderException("Each XMLConfigBuilder can only be used once.");
  4. }
  5. parsed = true;
  6. parseConfiguration(parser.evalNode("/configuration"));
  7. return configuration;
  8. }
  1. private void parseConfiguration(XNode root) {
  2. try {
  3. //issue #117 read properties first
  4. propertiesElement(root.evalNode("properties"));
  5. Properties settings = settingsAsProperties(root.evalNode("settings"));
  6. loadCustomVfs(settings);
  7. typeAliasesElement(root.evalNode("typeAliases"));
  8. pluginElement(root.evalNode("plugins"));
  9. objectFactoryElement(root.evalNode("objectFactory"));
  10. objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
  11. reflectorFactoryElement(root.evalNode("reflectorFactory"));
  12. settingsElement(settings);
  13. // read it after objectFactory and objectWrapperFactory issue #631
  14. environmentsElement(root.evalNode("environments"));
  15. databaseIdProviderElement(root.evalNode("databaseIdProvider"));
  16. typeHandlerElement(root.evalNode("typeHandlers"));
  17. mapperElement(root.evalNode("mappers"));
  18. } catch (Exception e) {
  19. throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
  20. }
  21. }

其中有一个二级缓存的解析就是

  1. mapperElement(root.evalNode("mappers"));

然后进去 mapperElement 方法中

  1. XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
  2. mapperParser.parse();

继续跟 mapperParser.parse() 方法

  1. public void parse() {
  2. if (!configuration.isResourceLoaded(resource)) {
  3. configurationElement(parser.evalNode("/mapper"));
  4. configuration.addLoadedResource(resource);
  5. bindMapperForNamespace();
  6. }
  7. parsePendingResultMaps();
  8. parsePendingCacheRefs();
  9. parsePendingStatements();
  10. }

这其中有一个 configurationElement 方法,它是对二级缓存进行创建,如下

  1. private void configurationElement(XNode context) {
  2. try {
  3. String namespace = context.getStringAttribute("namespace");
  4. if (namespace == null || namespace.equals("")) {
  5. throw new BuilderException("Mapper's namespace cannot be empty");
  6. }
  7. builderAssistant.setCurrentNamespace(namespace);
  8. cacheRefElement(context.evalNode("cache-ref"));
  9. cacheElement(context.evalNode("cache"));
  10. parameterMapElement(context.evalNodes("/mapper/parameterMap"));
  11. resultMapElements(context.evalNodes("/mapper/resultMap"));
  12. sqlElement(context.evalNodes("/mapper/sql"));
  13. buildStatementFromContext(context.evalNodes("select|insert|update|delete"));
  14. } catch (Exception e) {
  15. throw new BuilderException("Error parsing Mapper XML. Cause: " + e, e);
  16. }
  17. }

有两个二级缓存的关键点

  1. cacheRefElement(context.evalNode("cache-ref"));
  2. cacheElement(context.evalNode("cache"));

也就是说,mybatis 首先进行解析的是 cache-ref 标签,其次进行解析的是 cache 标签。

根据上面我们的 — 多表操作对二级缓存的影响 一节中提到的解决办法,采用 cache-ref 来进行命名空间的依赖能够避免二级缓存,但是总不能每次写一个 XML 配置都会采用这种方式吧,最有效的方式还是避免多表操作使用二级缓存

然后我们再来看一下cacheElement(context.evalNode("cache")) 这个方法

  1. private void cacheElement(XNode context) throws Exception {
  2. if (context != null) {
  3. String type = context.getStringAttribute("type", "PERPETUAL");
  4. Class<? extends Cache> typeClass = typeAliasRegistry.resolveAlias(type);
  5. String eviction = context.getStringAttribute("eviction", "LRU");
  6. Class<? extends Cache> evictionClass = typeAliasRegistry.resolveAlias(eviction);
  7. Long flushInterval = context.getLongAttribute("flushInterval");
  8. Integer size = context.getIntAttribute("size");
  9. boolean readWrite = !context.getBooleanAttribute("readOnly", false);
  10. boolean blocking = context.getBooleanAttribute("blocking", false);
  11. Properties props = context.getChildrenAsProperties();
  12. builderAssistant.useNewCache(typeClass, evictionClass, flushInterval, size, readWrite, blocking, props);
  13. }
  14. }

认真看一下其中的属性的解析,是不是感觉很熟悉?这不就是对 cache 标签属性的解析吗?!!!

上述最后一句代码

  1. builderAssistant.useNewCache(typeClass, evictionClass, flushInterval, size, readWrite, blocking, props);
  1. public Cache useNewCache(Class<? extends Cache> typeClass,
  2. Class<? extends Cache> evictionClass,
  3. Long flushInterval,
  4. Integer size,
  5. boolean readWrite,
  6. boolean blocking,
  7. Properties props) {
  8. Cache cache = new CacheBuilder(currentNamespace)
  9. .implementation(valueOrDefault(typeClass, PerpetualCache.class))
  10. .addDecorator(valueOrDefault(evictionClass, LruCache.class))
  11. .clearInterval(flushInterval)
  12. .size(size)
  13. .readWrite(readWrite)
  14. .blocking(blocking)
  15. .properties(props)
  16. .build();
  17. configuration.addCache(cache);
  18. currentCache = cache;
  19. return cache;
  20. }

这段代码使用了构建器模式,一步一步构建Cache 标签的所有属性,最终把 cache 返回。

6.2 二级缓存的使用

在 mybatis 中,使用 Cache 的地方在 CachingExecutor中,来看一下 CachingExecutor 中缓存做了什么工作,我们以查询为例

  1. @Override
  2. public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql)
  3. throws SQLException {
  4. // 得到缓存
  5. Cache cache = ms.getCache();
  6. if (cache != null) {
  7. // 如果需要的话刷新缓存
  8. flushCacheIfRequired(ms);
  9. if (ms.isUseCache() && resultHandler == null) {
  10. ensureNoOutParams(ms, parameterObject, boundSql);
  11. @SuppressWarnings("unchecked")
  12. List<E> list = (List<E>) tcm.getObject(cache, key);
  13. if (list == null) {
  14. list = delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
  15. tcm.putObject(cache, key, list); // issue #578 and #116
  16. }
  17. return list;
  18. }
  19. }
  20. // 委托模式,交给SimpleExecutor等实现类去实现方法。
  21. return delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
  22. }

其中,先从 MapperStatement 取出缓存。只有通过<cache/>,<cache-ref/>或@CacheNamespace,@CacheNamespaceRef标记使用缓存的Mapper.xml或Mapper接口(同一个namespace,不能同时使用)才会有二级缓存。

如果缓存不为空,说明是存在缓存。如果cache存在,那么会根据sql配置(<insert>,<select>,<update>,<delete>的flushCache属性来确定是否清空缓存。

  1. flushCacheIfRequired(ms);

然后根据xml配置的属性useCache来判断是否使用缓存(resultHandler一般使用的默认值,很少会null)。

  1. if (ms.isUseCache() && resultHandler == null)

确保方法没有Out类型的参数,mybatis不支持存储过程的缓存,所以如果是存储过程,这里就会报错。

  1. private void ensureNoOutParams(MappedStatement ms, Object parameter, BoundSql boundSql) {
  2. if (ms.getStatementType() == StatementType.CALLABLE) {
  3. for (ParameterMapping parameterMapping : boundSql.getParameterMappings()) {
  4. if (parameterMapping.getMode() != ParameterMode.IN) {
  5. throw new ExecutorException("Caching stored procedures with OUT params is not supported. Please configure useCache=false in " + ms.getId() + " statement.");
  6. }
  7. }
  8. }
  9. }

然后根据在 TransactionalCacheManager 中根据 key 取出缓存,如果没有缓存,就会执行查询,并且将查询结果放到缓存中并返回取出结果,否则就执行真正的查询方法。

  1. List<E> list = (List<E>) tcm.getObject(cache, key);
  2. if (list == null) {
  3. list = delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
  4. tcm.putObject(cache, key, list); // issue #578 and #116
  5. }
  6. return list;

7、是否应该使用二级缓存?

那么究竟应该不应该使用二级缓存呢?先来看一下二级缓存的注意事项:

  1. 缓存是以namespace为单位的,不同namespace下的操作互不影响。
  2. insert,update,delete操作会清空所在namespace下的全部缓存。
    通常使用MyBatis Generator生成的代码中,都是各个表独立的,每个表都有自己的namespace。
  3. 多表操作一定不要使用二级缓存,因为多表操作进行更新操作,一定会产生脏数据。
  4. 如果你遵守二级缓存的注意事项,那么你就可以使用二级缓存。

但是,如果不能使用多表操作,二级缓存不就可以用一级缓存来替换掉吗?而且二级缓存是表级缓存,开销大,没有一级缓存直接使用 HashMap 来存储的效率更高,所以二级缓存并不推荐使用。

相关文章