mybatis精講(六)--二級緩存


簡介

  • 上一章節我們簡單了解了二級緩存的配置。今天我們詳細分析下二級緩存以及為什么不建議使用二級緩存。

  • 一級緩存針對的是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.

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);

  • 但是結果確實很意外。事實上並沒有只調用一次sql。而是調用了兩次。這僅僅是結果上的異常。我們用的是Student這個結果接受的。我們再從代碼層面上看看

@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()

  • 這個地方就是進行緩存存儲的。我們再來看看mybatis是如何解析mapper.xml中配置的cache標簽的。


  • 由上面代碼我們得知mybatis會創建一個緩存對象。里面具體是通過一個build方法來創建的。我們在來看看build方法里是啥東西。

  • setStandardDecorators這個方法我們不知道做啥的。但是熟悉設計模式的都知道Decorator這個詞是裝飾者模式。這里這個方法也是用來裝飾用的。看看mybatis為我們裝飾了那些東西。

  • 首先在newBaseCacheInstance方法中創建原始對象PreprtualCache.然后是加載默認提供的回收機制用的Cache。這個實在build前設置的。
  • 然后就是通過setStandardDecorators進行裝飾了。

  • 所以他的裝飾鏈為: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 .

源碼

CachingExecutor


@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這個類作為基礎緩存類。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM