간결 및 (f)의 MyBatis - 보조 캐시

간략한 소개

  • 마지막 장에서는 우리는 단순히 보조 캐시 구성을 이해합니다. 우리는 오늘 second-level 캐시에서 자세히 분석하고 왜 L2 캐시의 사용을 권장하지 않습니다.

  • 레벨 캐시는 SQLSESSION 대상으로합니다. 네임 스페이스 수준에 대한 보조 캐시.

구성

  • 우리는 이전에 구성 함과 사용자 정의 보조 캐시 보조 캐시를 구성했다. 의 두 번째 레벨 캐시를 달성하기 위해 처음부터 시작하자.

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이 속성은 보조 캐시 제어의 구성입니다. 그리고이 구성 사실의 기본 속성입니다. 다음은 MyBatis로 캐싱 기능은 기본적으로 활성화되어 설명했다. 캐시 사실의 캐시 간의 차이의 범위에 더하여, 그 차이는 상이한 순서이다. 차 캐시는 XML 매퍼의 라인에 진정으로 개방 구성 캐시 태그입니다.

  • 우리는 그 다음 우리가 테스트 클래스에서 같은 전화를 두 번 SQLSESSION의 SQL을 얻을 StudentMapper.xml 여기에 구성.

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 번 호출되지 않습니다. 그러나 두 번 호출. 이 이상 단지 결과입니다. 우리는 학생이 결과를 받아 사용합니다. 우리가에서, 코드 수준에서 살펴 보자

@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;
}
  • 주의 파트너 찾을 수 있습니다. 우리는이 개체의 직렬화를 실현하지 않았다. 그러나 우리는 보조 캐시 개체 직렬화 할 필요가 전에 말했듯이. 논리적으로, 그것은 주어지는한다. 이 쇼는 우리의 보조 캐시가 켜져, 또는 정확하게, 두 번째 레벨 캐시 역할을하지 않는다고 말했다되어야한다.
  • 우리 제 1 개체 직렬화 그래서. 그런 다음 시작하고 영향을 찾을 수 없습니다. 우리는 좀 걸릴 CacheingExecutor.commit()이 방법 내부가 제출하는 일이있다 tcm.commit().

  • 이 장소는 캐시에 저장됩니다. 우리는 MyBatis로 해결 캐시 레이블 mapper.xml 구성하는 방법을 살펴 봅니다.


  • 위의 코드에서 우리는 MyBatis로는 캐시의 객체를 생성 배웠다. 어떤 빌드를 생성하는 특정 방법입니다. 우리는 일이 빌드 방법이 무엇인지 살펴보고.

  • 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这个类作为基础缓存类。

추천

출처www.cnblogs.com/zhangxinhua/p/12120202.html