看过Mybatis组织架构已经一段时间了,最近由于忙碌而忘记了很多细节,所以特此记录下来。
在软件开发过程,时时刻刻都在和缓存打交道,足以证明缓存对于当代软件系统架构的重要,本文带你揭开Mybatis的缓存面纱。
首先是SESSION级别的缓存,声明周期在一次会话中,具体实现为SqlSession将DB操作委托给Executor,而在抽象类中BaseExecutor具有一个成员变量,在构造方法中初始化,查询方法从缓存中查询,其他方法则移除缓存。部分代码逻辑示意入下:
/**成员变量
*/
protected PerpetualCache localCache;
/**
* 构造方法
*/
this.localCache = new PerpetualCache("LocalCache");
/**
* 查询方法
*/
List<E> query(){
list = resultHandler == null ? (List<E>) localCache.getObject(key) : null;
}
/**
* 清除缓存
*/
void clearLocalCache()
其次是STATEMENT级别的缓存,可以在多次会话中共享数据,具体实现是CachingExecutor装饰了Executor类,然后引入TransactionalCacheManager进行缓存管理。
public class CachingExecutor implements Executor {
private final Executor delegate;
int update (){
flushCacheIfRequired(ms);
return delegate.update(ms, parameterObject);
}
public <E> List<E> query(){
Cache cache = ms.getCache();
if (cache != null) {
flushCacheIfRequired(ms);
if (ms.isUseCache() && resultHandler == null) {
List<E> list = (List<E>) tcm.getObject(cache, key);
if (list == null) {
list = delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
tcm.putObject(cache, key, list); // issue #578 and #116
}
return list;
}
其中这个过程中利用装饰器去增强缓存的功能。
SynchronizedCache: 同步Cache,实现比较简单,直接使用synchronized修饰方法。
LoggingCache: 日志功能,装饰类,用于记录缓存的命中率,如果开启了DEBUG模式,则会输出命中率日志。
SerializedCache: 序列化功能,将值序列化后存到缓存中。该功能用于缓存返回一份实例的Copy,用于保存线程安全。
LruCache: 采用了Lru算法的Cache实现,移除最近最少使用的key/value。
PerpetualCache: 作为为最基础的缓存类,底层实现比较简单,直接使用了HashMap
但是二级缓存在多表查询中很容易出现脏数据,使用条件苛刻。而且现在是Redis和Memcache等分布式缓存中间件比较简单高效,所以项目中没有直接使用。