对着源码学mybatis系列——cacheEnabled

诚明聊代码2024-06-18 10:23:58  44

一、MyBatis 缓存机制

MyBatis 的缓存分为一级缓存和二级缓存:

一级缓存:也叫本地缓存,是 MyBatis 自带的,默认开启。它是基于 PerpetualCache 的 HashMap 本地缓存,存储作用域为 Session,当 Session flush 或 close 之后,该 Session 中的所有 Cache 就将清空。

二级缓存:也叫全局缓存,需要手动开启。它是基于 Cache 的 HashMap 全局缓存,存储作用域为 Mapper 级别,多个 SqlSession 去操作同一个 Mapper 的 sql 语句,多个 SqlSession 可以共用二级缓存,二级缓存是跨 SqlSession 的。

二、MyBatis 缓存使用

一级缓存:无需手动配置,MyBatis 会自动管理。但需要注意的是,如果在一个 Session 中执行了相同的 SQL 语句,MyBatis 会直接从缓存中获取结果,而不会再次执行 SQL 语句。

二级缓存:需要在 MyBatis 的配置文件中进行配置,例如:

在上面的配置中,我们将 cacheEnabled 设置为 true,表示开启二级缓存。然后,我们可以在 Mapper.xml 文件中使用 标签来配置二级缓存的相关属性,例如:

在上面的配置中,我们配置了二级缓存的一些属性:

eviction:缓存的回收策略,默认是 LRU(最近最少使用),还可以选择 FIFO(先进先出)、SOFT(软引用)、WEAK(弱引用)。

flushInterval:缓存的刷新间隔,单位是毫秒,默认是 60000(1 分钟)。

size:缓存的数量,默认是 1024。

readOnly:缓存是否只读,默认是 false。如果设置为 true,表示缓存是只读的,不会被修改。如果设置为 false,表示缓存是可读写的,会被修改。

需要注意的是,二级缓存是基于 Mapper 级别的,也就是说,不同的 Mapper 之间的缓存是相互独立的。如果需要在多个 Mapper 之间共享缓存,可以使用 Spring 等框架来管理 MyBatis 的二级缓存。

三、源码实现

Configuration类的newExecutor方法

public Executor newExecutor(Transaction transaction, ExecutorType executorType) { executorType = executorType == null ? defaultExecutorType : 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); } // 如果 cacheEnabled = true,则使用代理模式,创建一个CachingExecutor if (cacheEnabled) { executor = new CachingExecutor(executor); } return (Executor) interceptorChain.pluginAll(executor);}

转载此文是出于传递更多信息目的。若来源标注错误或侵犯了您的合法权益,请与本站联系,我们将及时更正、删除、谢谢。
https://www.414w.com/read/780691.html
0
最新回复(0)