Mybatis二级缓存知识汇总
2021-02-08 本文已影响0人
迦叶_金色的人生_荣耀而又辉煌
上一篇 <<<Mybatis一级缓存知识汇总
下一篇 >>>Springboot整合Mybatis二级缓存
1.底层实现原理
先请求二级缓存中的数据,不存在的话读取一级缓存,如果没有的话则从数据库中读取,之后分别缓存一级缓存和二级缓存。
二级缓存必须在session关闭或提交的时候,才会将数据真正写入缓存中,要不然都在一个临时的对象中。
Springboot自带拦截器,每次请求都会执行commit的操作,也就自动将数据存储到二级缓存中,不用手动去调用。

2.核心源码
// 读取
TransactionalCacheManager.getTransactionalCache(cache).getObject(key);
a、getTransactionalCache
txCache = new TransactionalCache(cache);
this.delegate = delegate; //对应的二级缓存对象
this.clearOnCommit = false;//是否在commit时清除二级缓存的标记
this.entriesToAddOnCommit = new HashMap();//需要在commit时提交到二级缓存的数据
this.entriesMissedInCache = new HashSet();//缓存未命中的数据,事务commit时,也会放入二级缓存
this.transactionalCaches.put(cache, txCache);
b、getObject
delegate.getObject(key);//调用真实缓存读取key对应的值
读取一级缓存或数据库后
CachingExecutor.his.tcm.putObject(cache, key, list);
TransactionalCacheManager.getTransactionalCache(cache).putObject(key, value);
TransactionalCacheManager.entriesToAddOnCommit.put(key, object);//先临时存放
sqlSession.close();/ sqlSession.commit();
CachingExecutor.tcm.commit();
Iterator i$ = CachingExecutor.transactionalCaches.values().iterator();
while(i$.hasNext()) {
TransactionalCache txCache = (TransactionalCache)i$.next();
txCache.commit();
{
TransactionalCache.flushPendingEntries();
TransactionalCache.reset();
}
}
//TransactionalCache.flushPendingEntries()的实现
将临时存放的数据写入到二级缓存中
private void flushPendingEntries() {
Iterator i$ = this.entriesToAddOnCommit.entrySet().iterator();
while(i$.hasNext()) {
Entry<Object, Object> entry = (Entry)i$.next();
this.delegate.putObject(entry.getKey(), entry.getValue());
}
i$ = this.entriesMissedInCache.iterator();
while(i$.hasNext()) {
Object entry = i$.next();
if (!this.entriesToAddOnCommit.containsKey(entry)) {
this.delegate.putObject(entry, (Object)null);
}
}
}
//TransactionalCache.reset();
重置临时存放的数据
private void reset() {
this.clearOnCommit = false;
this.entriesToAddOnCommit.clear();
this.entriesMissedInCache.clear();
}
推荐阅读:
<<<Mybatis的整体执行原理图解
<<<SqlSessionFactory的创建过程原理
<<<SqlSession的创建过程
<<<sqlSession如何获得具体的Mapper接口信息
<<<userMapper.getUser(1);底层实现原理
<<<sqlSession.selectOne底层实现原理
<<<Mybatis一级缓存知识汇总
<<<Springboot整合Mybatis二级缓存
<<<Mybatis常见面试题