Mybatis中的缓存机制(一文带你弄懂)

Mybatis中的缓存机制

概述

缓存的作⽤:通过减少IO的⽅式,来提⾼程序的执⾏效率。

缓存就是指存在内存中的临时数据,使用缓存能够减少和数据库交互的次数,提高效率。将相同查询条件的sql语句执行一遍后得到的结果存在内存或者某种缓存介质中,当下次遇到一模一样的查询sql时候不在执行sql与数据库交互,而是直接从缓存中获取结果,减少服

务器的压力;

mybatis缓存包括:

● ⼀级缓存:将查询到的数据存储到SqlSession中。范围比较小,正对于一次sql会话

● ⼆级缓存:将查询到的数据存储到SqlSessionFactory中。范围比较大,针对于整个数据库级别的。

● 或者集成其它第三⽅的缓存:⽐如EhCache【Java语⾔开发的】、Memcache【C语⾔开发的】等。
缓存只针对于DQL语句,也就是缓存机制只对应select语句。

项目结构

在这里插入图片描述
实体类

@Data
public class Student  implements Serializable {
    private Integer stuId;
    private String stuName;
    private Integer stuAge;
    private Double stuSalary;
    private Date stuBirth;
    private Date createTime;
    private Integer courseId;
}

接口StudentMapper

public interface StudentMapper {
     //通过id查询学生,传递单个参数
     Student queryStudentById(Integer id);
     //删除一条信息,通过id
     Integer delete(Integer id);
}

StudentMapper.xml映射文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!--namespace:Mapper接口的全路径,使其和Mapper对应-->
<mapper namespace="com.yjg.mapper.StudentMapper">
    <delete id="delete">
        DELETE from student where stu_id=${id}
    </delete>

    <select id="queryStudentById" parameterType="integer" resultType="Student">
          select * from student where stu_id=${id}
    </select>
</mapper>

MyBatis 一级缓存

一级缓存原理

⼀级缓存默认是开启的。不需要做任何配置。

在一次 SqlSession 中(数据库会话),程序执行多次查询,且查询条件完全相同,多次查询之间程序没有其他增删改操作,则第二次及后面的查询可以从缓存中获取数据,不会走数据库,会走缓存

代码测试

测试一

@Test
public void test1() throws Exception{
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis.xml"));
    SqlSession sqlSession1 = sqlSessionFactory.openSession();

    //只执行了一条sql语句
    StudentMapper mapper1 = sqlSession1.getMapper(StudentMapper.class);
    Student student1 = mapper1.queryStudentById(2);
    System.out.println(student1);

    Student student2 = mapper1.queryStudentById(2);
    System.out.println(student2);

    sqlSession1.close();
}

执行结果

执行结果只有一条select语句,但是存在两次查询结果,也就是说第二次是从缓存里面拿到的。
在这里插入图片描述
是否和getMapper 方法来获取接口的实例有关系呢

测试二

@Test
public void test3() throws Exception{
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis.xml"));
    SqlSession sqlSession1 = sqlSessionFactory.openSession();

    //只执行了一条sql语句
    //同一个sqlSession就会走一级缓存,跟mapper没有关系
    StudentMapper mapper1 = sqlSession1.getMapper(StudentMapper.class);
    Student student1 = mapper1.queryStudentById(2);
    System.out.println(student1);

    StudentMapper mapper2 = sqlSession1.getMapper(StudentMapper.class);
    Student student2 = mapper2.queryStudentById(2);
    System.out.println(student2);
    
    sqlSession1.close();
}

执行结果

执行结果发现还是和上面一样,所以和getMapper方法来获取接口的实例是没有关系的,只和sqlSession有关关系。
在这里插入图片描述
如果是两个不同的sqlSession结果还是一样的吗

@Test
public void test2() throws Exception{
    //一级缓存就是在一个sqlSession,这里获取了两个sqlSession不是同一个sqlSession,所以不会走缓存会在去查找一遍
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis.xml"));
    SqlSession sqlSession1 = sqlSessionFactory.openSession();
    SqlSession sqlSession2 = sqlSessionFactory.openSession();

    StudentMapper mapper1 = sqlSession1.getMapper(StudentMapper.class);
    Student student1 = mapper1.queryStudentById(2);
    System.out.println(student1);

    StudentMapper mapper2 = sqlSession2.getMapper(StudentMapper.class);
    Student student2 = mapper2.queryStudentById(2);
    System.out.println(student2);

    sqlSession1.close();
    sqlSession2.close();

}

执行结果

可以看到存在两个select语句,说明不同的sqlSession查询语句一样的时候不是从缓存里面获取的,还是从数据库来获取的。
在这里插入图片描述

什么时候一级缓存失效?

第一次DQL和第二次DQL之间你做了以下两件事中的任意一件,都会让一级缓存清空:
1.执行了sqlSession的clearCache()方法,这是手动清空缓存。
2.执行了INSERT或DELETE或UPDATE语句。不管你是操作哪张表的,都会清空一级缓存。

测试代码

执行了sqlSession的clearCache()方法

@Test
public void test4() throws Exception{
 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis.xml"));
    SqlSession sqlSession1 = sqlSessionFactory.openSession();

    StudentMapper mapper1 = sqlSession1.getMapper(StudentMapper.class);
    Student student1 = mapper1.queryStudentById(2);
    System.out.println(student1);

    //手动清空一级缓存  会执行两次查询,不会从一级缓存去取
    sqlSession1.clearCache();

    Student student2 = mapper1.queryStudentById(2);
    System.out.println(student2);

    sqlSession1.close();
}

执行结果

可以看到存在两个select语句,说明不是从一级缓存里面获取的,是从数据库获取的。
在这里插入图片描述
测试代码

执行了INSERT或DELETE或UPDATE语句

@Test
public void test4() throws Exception{
    //一级缓存就是在一个sqlSession,这里获取了两个sqlSession不是同一个sqlSession,所以不会走缓存会在去查找一遍
    SqlSessionFactory sqlSessionFactory = new    SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis.xml"));
    SqlSession sqlSession1 = sqlSessionFactory.openSession();

    StudentMapper mapper1 = sqlSession1.getMapper(StudentMapper.class);
    Student student1 = mapper1.queryStudentById(2);
    System.out.println(student1);

    //会使得下面查询时候不会去一级缓存里面去找
    Integer delete = mapper1.delete(16);

    Student student2 = mapper1.queryStudentById(2);
    System.out.println(student2);

    sqlSession1.close();

}

执行结果和上面一样还是会存在两个select语句

Mybatis二级缓存

二级缓存的范围是SqlSessionFactory。

使用二级缓存需要具备以下几个条件:

  1. <setting name="cacheEnabled" value="true"> 这个配置表示启用 MyBatis 的二级缓存功能。默认就是true,⽆需在配置文件设置。

  2. 在需要使⽤⼆级缓存的StudentMapper.xml⽂件中添加配置:<cache/>

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!--namespace:Mapper接口的全路径,使其和Mapper对应-->
<mapper namespace="com.yjg.mapper.StudentMapper">

    <!--    默认情况下,二级缓存机制是开启的。-->
    <!--    只需要在对应的StudentMapper.xml文件中添加以下标签。用来表示”我"使用该二级缓存。-->
    <cache/>
    
    <delete id="delete">
        DELETE from student where stu_id=${id}
    </delete>
    <select id="queryStudentById" parameterType="integer" resultType="Student">
          select * from student where stu_id=${id}
    </select>
</mapper>
  1. 使⽤⼆级缓存的实体类对象必须是可序列化的,也就是必须实现java.io.Serializable接⼝
@Data
public class Student  implements Serializable {
    private Integer stuId;
    private String stuName;
    private Integer stuAge;
    private Double stuSalary;
    private Date stuBirth;
    private Date createTime;
    private Integer courseId;
}
  1. SqlSession对象关闭或提交之后,⼀级缓存中的数据才会被写⼊到⼆级缓存当中。此时⼆级缓存才可⽤

测试代码

测试一

@Test
    public void test5() throws Exception{
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis.xml"));
        SqlSession sqlSession1 = sqlSessionFactory.openSession();
        SqlSession sqlSession2 = sqlSessionFactory.openSession();
        StudentMapper mapper1 = sqlSession1.getMapper(StudentMapper.class);
        StudentMapper mapper2 = sqlSession2.getMapper(StudentMapper.class);


        //这行代码执行结束之后,实际上数据是缓存到一级缓存当中了。(sqlSession1是一级缓存。>
        Student student1 = mapper1.queryStudentById(2);
        System.out.println(student1);

        //如果这里不关闭SqlSession1对象的话,二级缓存中还是没有数据的。

        //这行代码执行结束之后,实际上数据会缓存到一级缓存当中。(sqlSession2是一级缓存。)
        Student student2 = mapper2.queryStudentById(2);
        System.out.println(student2);

        //程序执行到这里的时候,会将sqlSession1这个一级缓存中的数据写入到二级缓存当中。
        sqlSession1.close();
        //程序执行到这里的时候,会将sqlSession2这个一级缓存中的数据写入到二级缓存当中。
        sqlSession2.close();

}

可以看见执行结果,存在一个Cache Hit Ratio [com.yjg.mapper.StudentMapper]: 0.0,就是因为在StudentMapper.xml文件中加了

可以看到,缓存命中率(Cache Hit Ratio)是0,执行了两个select语句,说明二级缓存没有生效
在这里插入图片描述
如果将关闭位置换一下,就可以让二级缓存生效

测试二

@Test
public void test5() throws Exception {
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis.xml"));
    SqlSession sqlSession1 = sqlSessionFactory.openSession();
    SqlSession sqlSession2 = sqlSessionFactory.openSession();
    StudentMapper mapper1 = sqlSession1.getMapper(StudentMapper.class);
    StudentMapper mapper2 = sqlSession2.getMapper(StudentMapper.class);


    //这行代码执行结束之后,实际上数据是缓存到一级缓存当中了。(sqlSession1是一级缓存。>
    Student student1 = mapper1.queryStudentById(2);
    System.out.println(student1);

    //程序执行到这里的时候,会将sqlSession1这个一级缓存中的数据写入到二级缓存当中。
    sqlSession1.close();

    //如果一级缓存中没有找到对应的缓存结果,MyBatis 会尝试从二级缓存中查找,发现存在就会使用二级缓存
    Student student2 = mapper2.queryStudentById(2);
    System.out.println(student2);


    //程序执行到这里的时候,会将sqlSession2这个一级缓存中的数据写入到二级缓存当中。
    sqlSession2.close();

}

总结这段代码

这段代码演示了一级缓存和二级缓存的使用。首次查询时会先从数据库查询并将结果放入一级缓存,在关闭 SqlSession 前会将一级缓存数据写入二级缓存。再次查询时,如果一级缓存没有找到结果,则会尝试从二级缓存中获取结果,避免了再次访问数据库。

执行结果

可见第二个缓存命中率是0.5,且只有一个select语句,说明了二级缓存生效了。
在这里插入图片描述

⼆级缓存的失效

⼆级缓存的失效:只要两次查询之间出现了增删改操作。⼆级缓存就会失效。【⼀级缓存也会失效】

⼆级缓存的相关配置

在这里插入图片描述
eviction:指定从缓存中移除某个对象的淘汰算法。默认采⽤LRU策略。

​ a. LRU:Least Recently Used。最近最少使⽤。优先淘汰在间隔时间内使⽤频率最低的对象。(还有⼀种淘汰算法LFU,最不常⽤。)

​ b. FIFO:First In First Out。⼀种先进先出的数据缓存器。先进⼊⼆级缓存的对象最先被淘汰。

​ c. SOFT:软引⽤。淘汰软引⽤指向的对象。具体算法和JVM的垃圾回收算法有关。

​ d. WEAK:弱引⽤。淘汰弱引⽤指向的对象。具体算法和JVM的垃圾回收算法有关。

flushInterval:

​ a. ⼆级缓存的刷新时间间隔。单位毫秒。如果没有设置。就代表不刷新缓存,只要内存⾜够⼤,⼀

​ 直会向⼆级缓存中缓存数据。除⾮执⾏了增删改。

readOnly:

​ a. true:多条相同的sql语句执⾏之后返回的对象是共享的同⼀个。性能好。但是多线程并发可能

​ 会存在安全问题。

​ b. false:多条相同的sql语句执⾏之后返回的对象是副本,调⽤了clone⽅法。性能⼀般。但安全。

size:

​ a. 设置⼆级缓存中最多可存储的java对象数量。默认值1024。

MyBatis集成EhCache

集成EhCache是为了代替mybatis⾃带的⼆级缓存。⼀级缓存是⽆法替代的。

mybatis对外提供了接⼝,也可以集成第三⽅的缓存组件。⽐如EhCache、Memcache等。都可以。

EhCache是Java写的。Memcache是C语⾔写的。所以mybatis集成EhCache较为常⻅,按照以下步骤操

作,就可以完成集成:

第⼀步:引⼊mybatis整合ehcache的依赖。

<!--mybatis集成ehcache的组件-->
<dependency>
 <groupId>org.mybatis.caches</groupId>
 <artifactId>mybatis-ehcache</artifactId>
 <version>1.2.2</version>
</dependency>
<!--ehcache需要slf4j的⽇志组件,log4j不好使-->
<dependency>
 <groupId>ch.qos.logback</groupId>
 <artifactId>logback-classic</artifactId>
 <version>1.2.11</version>
 <scope>test</scope>
</dependency>

第⼆步:在类的根路径下新建echcache.xml⽂件,并提供以下配置信息。

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
 updateCheck="false">
 <!--磁盘存储:将缓存中暂时不使⽤的对象,转移到硬盘,类似于Windows系统的虚拟内存-->
 <diskStore path="e:/ehcache"/>
 
 <!--defaultCache:默认的管理策略-->
 <!--eternal:设定缓存的elements是否永远不过期。如果为true,则缓存的数据始终有
效,如果为false那么还要根据timeToIdleSeconds,timeToLiveSeconds判断-->
 <!--maxElementsInMemory:在内存中缓存的element的最⼤数⽬-->
 <!--overflowToDisk:如果内存中数据超过内存限制,是否要缓存到磁盘上-->
 <!--diskPersistent:是否在磁盘上持久化。指重启jvm后,数据是否有效。默认为false-
->
 <!--timeToIdleSeconds:对象空闲时间(单位:秒),指对象在多⻓时间没有被访问就会失
效。只对eternal为false的有效。默认值0,表示⼀直可以访问-->
 <!--timeToLiveSeconds:对象存活时间(单位:秒),指对象从创建到失效所需要的时间。
只对eternal为false的有效。默认值0,表示⼀直可以访问-->
 <!--memoryStoreEvictionPolicy:缓存的3 种清空策略-->
 <!--FIFO:first in first out (先进先出)-->
 <!--LFU:Less Frequently Used (最少使⽤).意思是⼀直以来最少被使⽤的。缓存的元
素有⼀个hit 属性,hit 值最⼩的将会被清出缓存-->
 <!--LRU:Least Recently Used(最近最少使⽤). (ehcache 默认值).缓存的元素有⼀
个时间戳,当缓存容量满了,⽽⼜需要腾出地⽅来缓存新的元素的时候,那么现有缓存元素中时间戳
离当前时间最远的元素将被清出缓存-->
 <defaultCache eternal="false" maxElementsInMemory="1000" overflowToDis
k="false" diskPersistent="false"
 timeToIdleSeconds="0" timeToLiveSeconds="600" memoryStor
eEvictionPolicy="LRU"/>
</ehcache>

第三步:修改StudentMapper.xml⽂件中的标签,添加type属性

<cache type="org.mybatis.caches.ehcache.EhcacheCache"/> 

第四步:编写测试程序使⽤。

@Test
public void test5() throws Exception {
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis.xml"));
    SqlSession sqlSession1 = sqlSessionFactory.openSession();
    SqlSession sqlSession2 = sqlSessionFactory.openSession();
    StudentMapper mapper1 = sqlSession1.getMapper(StudentMapper.class);
    StudentMapper mapper2 = sqlSession2.getMapper(StudentMapper.class);
    Student student1 = mapper1.queryStudentById(2);
    System.out.println(student1);
    sqlSession1.close();
    Student student2 = mapper2.queryStudentById(2);
    System.out.println(student2);
    sqlSession2.close();

}

执行结果

二级缓存使用成功,只存在一条select语句,并且缓存第二个命中率不为0
在这里插入图片描述
参考网站
http://www.bjpowernode.com/javavideo.html

  • 10
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yjg_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值