首页 > IT职业 > IT职场 > mybatis精讲(六)--二级缓存
[TOC]
上一章节我们简单了解了二级缓存的配置。今天我们详细分析下二级缓存以及为什么不建议使用二级缓存。
一级缓存针对的是sqlsession。二级缓存针对的是namespace层面的。
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);
}
if (cacheEnabled) {
executor = new CachingExecutor(executor);
}
executor = (Executor) interceptorChain.pluginAll(executor);
return executor;
}
```
- 通过上面的代码我们可以看出来,`cacheEnabled`这个属性是控制二级缓存的配置的。而这个属性在Configuration中默认是true。这里说明了mybatis默认是开启缓存功能的。二级缓存和一级缓存的区别其实除了范围以外,他们的不同点就是顺序不同。真正开启二级缓存的是在mapper的xml中配置cache标签就行了。

- 我们这里在StudentMapper.xml中配置.然后我们在test类中进行获取两次sqlsession调用同一个sql.
```java
SqlSession sqlSession = SqlSessionFactoryUtils.openSqlsession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
Student student = mapper.getStudentByIdAndName("1", "1");
System.out.println(student);
SqlSession sqlSession1 = SqlSessionFactoryUtils.sqlSessionFactory.openSession();
StudentMapper mapper1 = sqlSession1.getMapper(StudentMapper.class);
Student studentByIdAndName = mapper1.getStudentByIdAndName("1", "1");
System.out.println(studentByIdAndName);
@Data
@Builder
@Accessors(chain = true)
public class Student {
/**
* 学生索引id
* */
* private String id;
* /**
* * 姓名
* */
* private String userName;
/**
* 用户昵称
* */
* private String userNick;
/**
* 年龄
* */
* private Integer age;
* /**
* * 性别 true : 男 ; false : 女
* */
* private SexEnum sex;
* /**
* * 生日
* */
* private Date birth;
* /**
* * 身高
* */
* private Double height;
* }
CacheingExecutor.commit()这个方法里面有事物的提交tcm.commit()。





所以他的装饰链为:SynchronizedCache->LogginCache->SerializedCache->LruCache->PerPetualCache
而在上面的tcm.commit就是在SerializedCache进行缓存对象的。所以我们之前的代码是sqlsession没有提交。所以代码只要稍微改动下。
SqlSession sqlSession = SqlSessionFactoryUtils.openSqlsession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
Student student = mapper.getStudentByIdAndName("1", "1");
System.out.println(student);
sqlSession.commit();
SqlSession sqlSession1 = SqlSessionFactoryUtils.sqlSessionFactory.openSession();
StudentMapper mapper1 = sqlSession1.getMapper(StudentMapper.class);
Student studentByIdAndName = mapper1.getStudentByIdAndName("1", "1");
System.out.println(studentByIdAndName);

SynchronizedCache : 同步Cache.这个类就是保证线程安全。所以他的方法基本上是加上synchronized来保证线程安全的。
LoggingCache : 日志。在上面我们有个日志是Cache Hit Ratio 0.5 表示二级缓存的命中率。
SerializedCache : 就是用来序列化数据的。
LruCache : 回收cache的算法
PerPetualCache :基本Cache .
@Override
public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql)
throws SQLException {
//获取Cache对象
Cache cache = ms.getCache();
if (cache != null) {
//根据statment配置刷新缓存,默认是insert、update、delete会刷新缓存
flushCacheIfRequired(ms);
//二级缓存开启入口。
if (ms.isUseCache() && resultHandler == null) {
//这个方法主要用来处理存储过程。后续章节说明
ensureNoOutParams(ms, boundSql);
@SuppressWarnings("unchecked")
//通过缓存事物查询数据
List<E> list = (List<E>) tcm.getObject(cache, key);
if (list == null) {
//调用委托类查询数据
list = delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
//加入缓存,供下次获取
tcm.putObject(cache, key, list);
}
return list;
}
}
//没有开启二级缓存则继续往下走
return delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
}
```
# 缺点
- 二级缓存因为更加广泛,所以容易造成脏数据。尤其是在关联查询的时候有序无法控制刷新力度。很容易出现脏读。

# 自定义二级缓存
- 在之前我们了解到的`PerpetualCache`是缓存链上最基本的缓存类。我们自定义的缓存就是替代这个类的。在mybatis中会现根据我们注册进来的类进行实例化。如果没有则用默认的`PerpetualCache`这个类作为基础缓存类。
-
> 本文由博客一文多发平台 [OpenWrite](https://openwrite.cn?from=article_bottom) 发布!
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/1276/viewspace-2824652/ ,如需转载,请注明出处,否则将追究法律责任。