作者:京东保险 王奕龙
本篇我们来讲 一级缓存,重点关注它的实现原理:何时生效、生效范围和何时失效,在未来设计缓存使用时,提供一些借鉴和参考。
1. 准备工作
定义实体
<!---->1public class Department { 2 3 public Department(String id) { 4 this.id = id; 5 } 6 7 private String id; 8 9 /** 10 * 部门名称 11 */ 12 private String name; 13 14 /** 15 * 部门电话 16 */ 17 private String tel; 18 19 /** 20 * 部门成员 21 */ 22 private Set<User> users; 23}
1public class User { 2 3 private String id; 4 5 private String name; 6 7 private Integer age; 8 9 private LocalDateTime birthday; 10 11 private Department department; 12}
定义 Mapper.xml
DepartmentMapper.xml,两条 SQL:一条根据 ID 查询;一条清除缓存,标记了 fulshCache 标签,将其设置为 true 后,只要语句被调用,都会将本地缓存和二级缓存清空(默认值为 false)
1<select id="findById" resultType="Department"> 2 select * from department 3 where id = #{id} 4</select> 5 6<select id="cleanCathe" resultType="int" flushCache="true"> 7 select count(department.id) from department; 8</select>
UserMapper.xml,联表查询用户信息:
1<select id="findAll" resultMap="userMap"> 2 select u.*, td.id, td.name as department_name 3 from user u 4 left join department td 5 on u.department_id = td.id 6</select>
2. 一级缓存
一级缓存的生效范围 SqlSession 级别的,不同 SqlSession 间不共享缓存,它默认情况下是启用的。主要作用是减少在同一个查询 SQL 会话中对数据库的重复查询,从而提高性能。以如下用例为例:
1 public static void main(String[] args) throws IOException { 2 InputStream xml = Resources.getResourceAsStream("mybatis-config.xml"); 3 SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder(); 4 // 开启二级缓存需要在同一个SqlSessionFactory下,二级缓存存在于 SqlSessionFactory 生命周期,如此才能命中二级缓存 5 SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(xml); 6 7 SqlSession sqlSession = sqlSessionFactory.openSession(); 8 DepartmentMapper departmentMapper = sqlSession.getMapper(DepartmentMapper.class); 9 System.out.println("----------department第一次查询 ↓------------"); 10 departmentMapper.findById("18ec781fbefd727923b0d35740b177ab"); 11 System.out.println("----------department一级缓存生效,控制台看不见SQL ↓------------"); 12 departmentMapper.findById("18ec781fbefd727923b0d35740b177ab"); 13 14 }
可以发现在第二次查询时,一级缓存生效,控制台没有出现SQL:

而我们清空下一级缓存再试试:
1 public static void main(String[] args) throws IOException { 2 InputStream xml = Resources.getResourceAsStream("mybatis-config.xml"); 3 SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder(); 4 // 开启二级缓存需要在同一个SqlSessionFactory下,二级缓存存在于 SqlSessionFactory 生命周期,如此才能命中二级缓存 5 SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(xml); 6 7 SqlSession sqlSession = sqlSessionFactory.openSession(); 8 DepartmentMapper departmentMapper = sqlSession.getMapper(DepartmentMapper.class); 9 System.out.println("----------department第一次查询 ↓------------"); 10 departmentMapper.findById("18ec781fbefd727923b0d35740b177ab"); 11 System.out.println("----------department一级缓存生效,控制台看不见SQL ↓------------"); 12 departmentMapper.findById("18ec781fbefd727923b0d35740b177ab"); 13 System.out.println("----------清除一级缓存 ↓------------"); 14 departmentMapper.cleanCathe(); 15 System.out.println("----------清除后department再一次查询,SQL再次出现 ↓------------"); 16 departmentMapper.findById("18ec781fbefd727923b0d35740b177ab"); 17 }
控制台日志很清晰,清除缓存后又重新查了一遍:

接下来我们看一下不同 SqlSession 间一级缓存是否共享,创建一个新的 SqlSession sqlSession1 执行相同的SQL:
1 public static void main(String[] args) throws IOException { 2 SqlSession sqlSession = sqlSessionFactory.openSession(); 3 SqlSession sqlSession1 = sqlSessionFactory.openSession(); 4 DepartmentMapper departmentMapper = sqlSession.getMapper(DepartmentMapper.class); 5 DepartmentMapper departmentMapper1 = sqlSession1.getMapper(DepartmentMapper.class); 6 System.out.println("----------department第一次查询 ↓------------"); 7 departmentMapper.findById("18ec781fbefd727923b0d35740b177ab"); 8 System.out.println("----------sqlSession1下department执行相同的SQL,控制台出现SQL ↓------------"); 9 departmentMapper1.findById("18ec781fbefd727923b0d35740b177ab"); 10 }
如控制台日志所示,可以发现在不同的 SqlSession 下不共享一级缓存:

3. 一级缓存原理
一级缓存在查询方法 org.apache.ibatis.executor.BaseExecutor#query 中生效,如下所示:
1public abstract class BaseExecutor implements Executor { 2 // ... 3 4 // 一级缓存 5 protected PerpetualCache localCache; 6 7 public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, 8 CacheKey key, BoundSql boundSql) throws SQLException { 9 ErrorContext.instance().resource(ms.getResource()).activity("executing a query").object(ms.getId()); 10 if (closed) { 11 throw new ExecutorException("Executor was closed."); 12 } 13 // 判断是否刷新本地缓存 14 if (queryStack == 0 && ms.isFlushCacheRequired()) { 15 clearLocalCache(); 16 } 17 List<E> list; 18 try { 19 queryStack++; 20 // 判断一级缓存是否存在,存在则直接作为结果返回,否则查询数据库 21 list = resultHandler == null ? (List<E>) localCache.getObject(key) : null; 22 if (list != null) { 23 // 存储过程相关逻辑 24 handleLocallyCachedOutputParameters(ms, key, parameter, boundSql); 25 } else { 26 // 未命中一级缓存,查询数据库 27 list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql); 28 } 29 } finally { 30 queryStack--; 31 } 32 if (queryStack == 0) { 33 for (DeferredLoad deferredLoad : deferredLoads) { 34 deferredLoad.load(); 35 } 36 // issue #601 37 deferredLoads.clear(); 38 if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) { 39 // issue #482 40 clearLocalCache(); 41 } 42 } 43 return list; 44 } 45 46 private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, 47 ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException { 48 List<E> list; 49 // 一级缓存占位 50 localCache.putObject(key, EXECUTION_PLACEHOLDER); 51 try { 52 list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql); 53 } finally { 54 // 查询完成后清除一级缓存 55 localCache.removeObject(key); 56 } 57 // 添加到一级缓存中 58 localCache.putObject(key, list); 59 // 存储过程相关逻辑 60 if (ms.getStatementType() == StatementType.CALLABLE) { 61 localOutputParameterCache.putObject(key, parameter); 62 } 63 return list; 64 } 65}
其中 PerpetualCache localCache 便是一级缓存,它的实现借助了 HashMap:
1public class PerpetualCache implements Cache { 2 3 private final String id; 4 5 private final Map<Object, Object> cache = new HashMap<>(); 6 7 // ... 8}
一级缓存生效的逻辑也非常简单,如下所示:

queryFromDatabase 方法中有一段蛮有意思的逻辑 localCache.putObject(key, EXECUTION_PLACEHOLDER);:在添加一级缓存前会先添加缓存 占位符 EXECUTION_PLACEHOLDER,但是这个占位符并没有被用作一个明确的同步机制来阻止其他线程的查询执行,所以它只是标记一个查询正在进行,提供了 防止在同一事务上下文中重复执行相同的查询的 基础,这种设计可能是 MyBatis 开发者认为在多数情况下,数据库查询的开销相对较小或同一事务中几乎不执行多次相同的查询,而不是为了在多线程环境下保证不击穿数据库,降低数据库的压力。
这种设计模式在分布式缓存系统中很常见,一般用于 解决 ”缓存击穿“ 问题,帮助系统在高并发环境下保持稳定性。
一级缓存失效场景
- 两次相同查询SQL间有 Insert、Delete、Update 语句执行时:Insert、Delete、Update 的 flushCache标签 默认为 true ,执行它们时,会将一级缓存清空
- 调用
sqlSession#clearCache方法 SqlSession被关闭时,一级缓存也会被清空
缓存的是对象的引用
以如下代码为例,第一次查询结果中 name 字段的值为 null,将其赋值再进行第二次查询:
1 System.out.println("----------department第一次查询 ↓------------"); 2 Department department = departmentMapper.findById("18ec781fbefd727923b0d35740b177ab"); 3 System.out.println(department); 4 department.setName(" 把名字改了"); 5 6 System.out.println("----------department一级缓存生效,控制台看不见SQL ↓------------"); 7 System.out.println(departmentMapper.findById("18ec781fbefd727923b0d35740b177ab"));
可以发现第二次查询取缓存的结果是 更改name结果之后的:

这是因为一级缓存中 存放的数据其实是对象的引用,导致第二次从一级缓存中查询到的数据,就是我们刚刚改过的数据,而并不是数据库中真实的数据。在同一个 SqlSession 中,如果对缓存中返回的对象进行了修改,而没有同步更新数据库,那么在后续的查询中会返回被修改的对象,而不是数据库中的最新数据,导致脏读。
4. 总结
- 一级缓存基于
SqlSession,不同SqlSession间不共享一级缓存 - 一级缓存被保存在
BaseExecutor的PerpetualCache中,本质上是HashMap - 执行 Insert、Delete、Update 语句会使一级缓存失效
- 一级缓存存放的数据是对象的引用,若对它进行修改,则之后取出的缓存为修改后的数据
