【MyBatis-07】MyBatis的缓存

一、MyBatis的一级缓存

一级缓存是SqlSession级别的,默认开启,通过同一个SqlSession查询的数据会被缓存,下次查询相同的数据,就会从缓存中直接获取,不会从数据库重新访问(即不会重新执行sql语句

1.1 一级缓存失效的四种情况:
  1. 不同的SqlSession对应不同的一级缓存
  2. 同一个SqlSession但是查询条件不同
  3. 同一个SqlSession两次查询期间执行了任何一次增删改操作
  4. 同一个SqlSession两次查询期间手动清空了缓存(sqlSession.clearCache();

二、MyBatis的二级缓存

二级缓存是SqlSessionFactory级别,通过同一个SqlSessionFactory创建的SqlSession查询的结果会被缓存;此后若再次执行相同的查询语句,结果就会从缓存中获取

2.1 二级缓存开启的条件
  1. 在核心配置文件中,设置全局配置属性cacheEnabled=“true”,默认为true,不需要设置
  2. 在映射文件中设置标签<cache />
  3. 二级缓存必须在SqlSession关闭或提交之后有效
  4. 查询的数据所转换的实体类类型必须实现序列化的接口

注:

  • sqlSession .commit( ) 提交事务
  • sqlSession .close( ) 关闭 sqlSession
  1. 在没有关闭sqlSession或没有提交sqlSession时会被保留在以及缓存
  2. 在关闭sqlSession或提交sqlSession后会被保留在以及缓存
2.2 二级缓存失效的条件
- 两次查询之间执行了任意的增删改,会使一级和二级缓存同时失效

测试二级缓存:

//测试二级缓存wo
    @Test
    public void testTwoCache() {
        try {
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            SqlSession sqlSession1 = sqlSessionFactory.openSession(true);
            CacheMapper mapper1 = sqlSession1.getMapper(CacheMapper.class);
            System.out.println(mapper1.getEmpByEid(1));
            sqlSession1.close();
            SqlSession sqlSession2 = sqlSessionFactory.openSession(true);
            CacheMapper mapper2 = sqlSession2.getMapper(CacheMapper.class);
            System.out.println(mapper2.getEmpByEid(1));
            sqlSession2.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

成功结果:

DEBUG 04-20 14:55:53,246 Cache Hit Ratio [cn.dhu.mybatis.mapper.CacheMapper]: 0.0 (LoggingCache.java:60) 
DEBUG 04-20 14:55:54,005 ==>  Preparing: select * from t_emp where eid = ? (BaseJdbcLogger.java:137) 
DEBUG 04-20 14:55:54,052 ==> Parameters: 1(Integer) (BaseJdbcLogger.java:137) 
DEBUG 04-20 14:55:54,088 <==      Total: 1 (BaseJdbcLogger.java:137) 
Emp{eid=1, empName='张三', age=23, sex='男', email='12@qq.com', dept=null}
WARN  04-20 14:55:54,139 As you are using functionality that deserializes object streams, it is recommended to define the JEP-290 serial filter. Please refer to https://docs.oracle.com/pls/topic/lookup?ctx=javase15&id=GUID-8296D8E8-2B93-4B9A-856E-0A65AF9B8C66 (SerialFilterChecker.java:45) 
DEBUG 04-20 14:55:54,149 Cache Hit Ratio [cn.dhu.mybatis.mapper.CacheMapper]: 0.5 (LoggingCache.java:60) 
Emp{eid=1, empName='张三', age=23, sex='男', email='12@qq.com', dept=null}

无二级缓存:

DEBUG 04-20 14:58:36,719 Cache Hit Ratio [cn.dhu.mybatis.mapper.CacheMapper]: 0.0 (LoggingCache.java:60) 
DEBUG 04-20 14:58:37,499 ==>  Preparing: select * from t_emp where eid = ? (BaseJdbcLogger.java:137) 
DEBUG 04-20 14:58:37,546 ==> Parameters: 1(Integer) (BaseJdbcLogger.java:137) 
DEBUG 04-20 14:58:37,586 <==      Total: 1 (BaseJdbcLogger.java:137) 
Emp{eid=1, empName='张三', age=23, sex='男', email='12@qq.com', dept=null}
DEBUG 04-20 14:58:37,590 Cache Hit Ratio [cn.dhu.mybatis.mapper.CacheMapper]: 0.0 (LoggingCache.java:60) 
DEBUG 04-20 14:58:37,645 ==>  Preparing: select * from t_emp where eid = ? (BaseJdbcLogger.java:137) 
DEBUG 04-20 14:58:37,645 ==> Parameters: 1(Integer) (BaseJdbcLogger.java:137) 
DEBUG 04-20 14:58:37,647 <==      Total: 1 (BaseJdbcLogger.java:137) 
Emp{eid=1, empName='张三', age=23, sex='男', email='12@qq.com', dept=null}
2.3 二级缓存的相关配置
  • 在mapper配置文件中添加的cache标签可以设置一些属性
  • eviction属性: 缓存回收策略
    • LRU(Least Recently Used) – 最近最少使用的:移除最长时间不被使用的对象。
    • FIFO(First in First out) – 先进先出:按对象进入缓存的顺序来移除它们。
    • SOFT – 软引用:移除基于垃圾回收器状态和软引用规则的对象。
    • WEAK – 弱引用:更积极地移除基于垃圾收集器状态和弱引用规则的对象。
    • 默认的是 LRU
  • flushInterval属性: 刷新间隔,单位毫秒
    • 默认情况是不设置,也就是没有刷新间隔,缓存仅仅调用语句(增删改)时刷新
  • size属性: 引用数目,正整数
    • 代表缓存最多可以存储多少个对象,太大容易导致内存溢出
  • readOnly属性: 只读,true/false
    • true:只读缓存;会给所有调用者返回缓存对象的相同实例。因此这些对象不能被修改。这提供了很重要的性能优势。
    • false:读写缓存;会返回缓存对象的拷贝(通过序列化)。这会慢一些,但是安全,因此默认是false

三、MyBatis缓存查询的顺序

  • 先查询二级缓存,因为二级缓存中可能会有其他程序已经查出来的数据,可以拿来直接使用
  • 如果二级缓存没有命中,再查询一级缓存
  • 如果一级缓存也没有命中,则查询数据库
  • SqlSession关闭之后,一级缓存中的数据会写入二级缓存

四、整合第三方缓存EHCache(了解)

4.1 添加依赖
<!-- Mybatis EHCache整合包 -->
<dependency>
	<groupId>org.mybatis.caches</groupId>
	<artifactId>mybatis-ehcache</artifactId>
	<version>1.2.1</version>
</dependency>
<!-- slf4j日志门面的一个具体实现 -->
<dependency>
	<groupId>ch.qos.logback</groupId>
	<artifactId>logback-classic</artifactId>
	<version>1.2.3</version>
</dependency>

在这里插入图片描述

4.2 创建EHCache的配置文件ehcache.xml
  • 名字必须叫ehcache.xml
<?xml version="1.0" encoding="utf-8" ?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
    <!-- 磁盘保存路径 -->
    <diskStore path="F:\Output\ehcache"/>
    <defaultCache
            maxElementsInMemory="1000"
            maxElementsOnDisk="10000000"
            eternal="false"
            overflowToDisk="true"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
    </defaultCache>
</ehcache>
4.3 设置二级缓存的类型
  • 在xxxMapper.xml文件中设置二级缓存类型
<cache type="org.mybatis.caches.ehcache.EhcacheCache" />
4.4 加入logback日志
  • 存在SLF4J时,作为简易日志的log4j将失效,此时我们需要借助SLF4J的具体实现logback来打印日志。创建logback的配置文件logback.xml,名字固定,不可改变
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
    <!-- 指定日志输出的位置 -->
    <appender name="STDOUT"
              class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <!-- 日志输出的格式 -->
            <!-- 按照顺序分别是:时间、日志级别、线程名称、打印日志的类、日志主体内容、换行 -->
            <pattern>[%d{HH:mm:ss.SSS}] [%-5level] [%thread] [%logger] [%msg]%n</pattern>
        </encoder>
    </appender>
    <!-- 设置全局日志级别。日志级别按顺序分别是:DEBUG、INFO、WARN、ERROR -->
    <!-- 指定任何一个日志级别都只打印当前级别和后面级别的日志。 -->
    <root level="DEBUG">
        <!-- 指定打印日志的appender,这里通过“STDOUT”引用了前面配置的appender -->
        <appender-ref ref="STDOUT" />
    </root>
    <!-- 根据特殊需求指定局部日志级别 -->
    <logger name="com.atguigu.crowd.mapper" level="DEBUG"/>
</configuration>
4.5 测试(和二级缓存测试一样)
//测试二级缓存wo
    @Test
    public void testTwoCache() {
        try {
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            SqlSession sqlSession1 = sqlSessionFactory.openSession(true);
            CacheMapper mapper1 = sqlSession1.getMapper(CacheMapper.class);
            System.out.println(mapper1.getEmpByEid(1));
            sqlSession1.close();
            SqlSession sqlSession2 = sqlSessionFactory.openSession(true);
            CacheMapper mapper2 = sqlSession2.getMapper(CacheMapper.class);
            System.out.println(mapper2.getEmpByEid(1));
            sqlSession2.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

本文主要参考:
【尚硅谷】2022版MyBatis教程(细致全面,快速上手)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值