栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【Mybatis源码】一级缓存

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【Mybatis源码】一级缓存

一级缓存,也被称为本地缓存。
一级缓存的作用:Mybatis默认的会话级别的缓存。
在同一个SqlSession中,如果有相同的SQL查询(相同的SQL和参数),会优先从缓存中查找,缓存中没有查询到再去数据库中查找,最后放到缓存。

Mybatis一级缓存的数据结构

Mybatis的一级缓存由存储在执行器 BaseExecutor.class 中的 localCache 和 localOutputParameterCache 实现,类名为 PerpetualCache.class。

public abstract class BaseExecutor implements Executor {

  private static final Log log = LogFactory.getLog(BaseExecutor.class);

  protected Transaction transaction;
  protected Executor wrapper;

  protected ConcurrentLinkedQueue deferredLoads;
  // 本地缓存
  protected PerpetualCache localCache;
  // StateMentType声明为CALLABLE时的缓存,调用存储过程一般较少,本文不多赘述
  protected PerpetualCache localOutputParameterCache;
  protected Configuration configuration;

  protected int queryStack;
  private boolean closed;

  protected BaseExecutor(Configuration configuration, Transaction transaction) {
    this.transaction = transaction;
    this.deferredLoads = new ConcurrentLinkedQueue<>();
    // id为LocalCache
    this.localCache = new PerpetualCache("LocalCache");
    // id为LocalOutPutParameterCache
    this.localOutputParameterCache = new PerpetualCache("LocalOutputParameterCache");
    this.closed = false;
    this.configuration = configuration;
    this.wrapper = this;
  }
  ......
}

再进入 PerpetualCache.class 的定义,可以看到 PerpetualCache 是实现了 Cache.class 接口,成员变量有 id 和一个 map 的类。

public class PerpetualCache implements Cache {

  private final String id;

  private final Map cache = new HashMap<>();

  public PerpetualCache(String id) {
    this.id = id;
  }

其中 Cache.class 接口定义如下:

public interface Cache {
  
  String getId();
  
  void putObject(Object key, Object value);
  
  Object getObject(Object key);
  
  Object removeObject(Object key);
  
  void clear();
  
  int getSize();
  
  default ReadWriteLock getReadWriteLock() {
    return null;
  }
}

由 Cache.class 的定义可知,id是Cache的唯一标识。

为什么需要唯一标识?
因为框架内实现Cache接口的类,以及它们的对象有很多,所以要用id区分。
在BaseExecutor的构造方法中可知,此处有两个id:LocalCache和LocalOutputParameterCache

Mybatis的一级缓存为什么是SqlSession级别的

Mybatis利用工厂模式,SqlSessionFactory 在每次创建 SqlSession 的时候,都会指定一个新的 Executor 。
源码如下:
org.apache.ibatis.session.defaults.DefaultSqlSessionFactory#openSessionFromDataSource

private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
    Transaction tx = null;
    try {
      final Environment environment = configuration.getEnvironment();
      final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
      tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
      // 根据配置类,获得一个新的Executor
      final Executor executor = configuration.newExecutor(tx, execType);
      return new DefaultSqlSession(configuration, executor, autoCommit);
    } catch (Exception e) {
      closeTransaction(tx); // may have fetched a connection so lets call close()
      throw ExceptionFactory.wrapException("Error opening session.  Cause: " + e, e);
    } finally {
      ErrorContext.instance().reset();
    }
  }

org.apache.ibatis.session.Configuration#newExecutor

public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
    // 取出用户指定的Executor类型,如果没有指定就用默认的SIMPLE
    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;
  }
Mybatis怎么判断一级缓存是否命中?

在 org.apache.ibatis.executor.BaseExecutor#query 中,会创建一个 CacheKey 。

@Override
  public  List query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
    BoundSql boundSql = ms.getBoundSql(parameter);
    CacheKey key = createCacheKey(ms, parameter, rowBounds, boundSql);
    return query(ms, parameter, rowBounds, resultHandler, key, boundSql);
  }

创建 CacheKey 的过程,源代码如下:

@Override
  public CacheKey createCacheKey(MappedStatement ms, Object parameterObject, RowBounds rowBounds, BoundSql boundSql) {
    if (closed) {
      throw new ExecutorException("Executor was closed.");
    }
    CacheKey cacheKey = new CacheKey();
    // 追加msid
    cacheKey.update(ms.getId());
    // 追加分页偏移
    cacheKey.update(rowBounds.getOffset());
    // 追加分页大小
    cacheKey.update(rowBounds.getLimit());
    // 追加SQL语句
    cacheKey.update(boundSql.getSql());
    List parameterMappings = boundSql.getParameterMappings();
    TypeHandlerRegistry typeHandlerRegistry = ms.getConfiguration().getTypeHandlerRegistry();
    // mimic DefaultParameterHandler logic
    for (ParameterMapping parameterMapping : parameterMappings) {
      if (parameterMapping.getMode() != ParameterMode.OUT) {
        Object value;
        String propertyName = parameterMapping.getProperty();
        // 获取参数值
        if (boundSql.hasAdditionalParameter(propertyName)) {
          value = boundSql.getAdditionalParameter(propertyName);
        } else if (parameterObject == null) {
          value = null;
        } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
          value = parameterObject;
        } else {
          MetaObject metaObject = configuration.newMetaObject(parameterObject);
          value = metaObject.getValue(propertyName);
        }
        // 追加参数值
        cacheKey.update(value);
      }
    }
    if (configuration.getEnvironment() != null) {
      // issue #176
      cacheKey.update(configuration.getEnvironment().getId());
    }
    return cacheKey;
  }

由源码可知, CacheKey由4种参数有关:MappedStatement 的id,分页信息(RowBounds 的 offset 和 limit ),BoundSql 的SQL语句,参数值。
拿到 CacheKey 之后,Mybatis进行以下处理:

  @SuppressWarnings("unchecked")
  @Override
  public  List query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
    ErrorContext.instance().resource(ms.getResource()).activity("executing a query").object(ms.getId());
    if (closed) {
      throw new ExecutorException("Executor was closed.");
    }
    // 如果语句声明了 flushCache=true,就清除一级缓存
    if (queryStack == 0 && ms.isFlushCacheRequired()) {
      clearLocalCache();
    }
    List list;
    try {
      queryStack++;
      // 去一级缓存中,根据key去查找value
      list = resultHandler == null ? (List) localCache.getObject(key) : null;
      // 如果命中了一级缓存,就从缓存中处理
      if (list != null) {
        // 如果是CALLABLE的调用存储过程的语句,加一些额外处理
        handleLocallyCachedOutputParameters(ms, key, parameter, boundSql);
      }
      // 如果没有命中一级缓存,就去数据库中查找 
      else {
        list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);
      }
    } finally {
      queryStack--;
    }
    if (queryStack == 0) {
      for (DeferredLoad deferredLoad : deferredLoads) {
        deferredLoad.load();
      }
      // issue #601
      deferredLoads.clear();
      // 如果localCache的作用域是STATEMENT级别,就清除一级缓存
      if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) {
        // issue #482
        clearLocalCache();
      }
    }
    return list;
  }

根据 CacheKey 去查询一级缓存中查询,如果没查询到再去数据库中查询 queryFromDatabase。

Mybatis从数据库中查询并填充缓存
private  List queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
    List list;
    // 先给这个key设置一个占位符
    localCache.putObject(key, EXECUTION_PLACEHOLDER);
    try {
      // 去查询数据库
      list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql);
    } finally {
      // 移除这个key
      localCache.removeObject(key);
    }
    // 把key和查询出的list放入本地缓存
    localCache.putObject(key, list);
    // 如果是CALLABLE的存储过程调用,还要放入localOutputParameterCache
    if (ms.getStatementType() == StatementType.CALLABLE) {
      localOutputParameterCache.putObject(key, parameter);
    }
    return list;
  }

真正执行数据库查询之前,先给这个key放置了一个占位value,在finally块把查询前放置的key删除。然后把key和真正从数据库中查出来的list放入一级缓存

一级缓存的失效场景

一级缓存的失效方法是 org.apache.ibatis.executor.BaseExecutor#clearLocalCache :

  @Override
  public void clearLocalCache() {
    if (!closed) {
      localCache.clear();
      localOutputParameterCache.clear();
    }
  }

只要在 BaseExecutor.class 找到 clearLoaclCache 调用的地方,就可以看到失效场景。

场景1:SqlSession.update 执行update操作(增删改), SqlSession 内部调用 BaseExecutor.update 。
场景2:查询的时候声明了 flushCache = true
场景3:在mybatis-settings文件中声明 localCache 的 scope 为 STATEMENT :

场景4:SqlSession.commit 事务提交的时候,SqlSession内调用 BaseExecutor.commit。

场景5:SqlSession.rollback事务回滚的时候,SqlSession内部调用 BaseExecutor.rollback 。

场景6 :SqlSession.close 关闭会话的时候,SqlSession内部调用 BaseExecutor.close, BaseExecutor.close又调用 BaseExecutor.rollback 。

场景7:SqlSession.closeCache

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/952634.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号