上一篇 <<<Mybatis一级缓存知识汇总
下一篇 >>>Springboot整合Mybatis二级缓存
1.底层实现原理
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常见面试题