目录
缓存
MyBatis 内置了一个强大的事务性查询缓存机制,它可以非常方便地配置和定制。 为了使它更加强大而且易于配置,我们对 MyBatis 3 中的缓存实现进行了许多改进。
默认情况下,只启用了本地的会话缓存,它仅仅对一个会话中的数据进行缓存。也叫做一级缓存
要启用全局的二级缓存,只需要在你的 SQL 映射文件中添加一行
<!--二级缓存开启-->
<cache/>
一级缓存:线程级别的缓存,是本地缓存,sqlSession级别的缓存
二级缓存:全局范围的缓存,不止局限于当前会话
一级缓存
@Test
public void testGetAllStu(){
TeacherDao mapper = sqlSession.getMapper(TeacherDao.class);
List<Student> allStu = mapper.getAllStu();
System.out.println(allStu.toString());
System.out.println("---------------------------");
List<Student> allStu2 = mapper.getAllStu();
System.out.println(allStu2.toString());
sqlSession.close();
}
测试结果
根据以上可以看出,调用了两次sql,但是只执行了一次。这就是mybatis的的一级缓存
正常情况在一级缓存是存在的,但是在某些操作下会导致缓存失败
1. 用不同的sql会话去查询。
@Test
public void testGetAllStu(){
TeacherDao mapper = sqlSession.getMapper(TeacherDao.class);
List<Student> allStu = mapper.getAllStu();
System.out.println(allStu.toString());
System.out.println("---------------------------");
TeacherDao mapper2 = sqlSession.getMapper(TeacherDao.class);
List<Student> allStu2 = mapper2.getAllStu();
System.out.println(allStu2.toString());
sqlSession.close();
}
2. 调用相同的sql,但是每次穿入的参数不一致也会导致缓存失效
@Test
public void testGetAllStu(){
SqlSession sqlSession = sqlSessionFactory.openSession();
TeacherDao mapper = sqlSession.getMapper(TeacherDao.class);
List<Student> allStu = mapper.getAllStu();
System.out.println(allStu.toString());
System.out.println("---------------------------");
SqlSession sqlSession1 = sqlSessionFactory.openSession();
TeacherDao mapper2 = sqlSession1.getMapper(TeacherDao.class);
List<Student> allStu2 = mapper2.getAllStu();
System.out.println(allStu2.toString());
sqlSession.close();
}
3. 两次调用的中数据发生变更。
@Test
public void testGetAllStu(){
TeacherDao mapper = sqlSession.getMapper(TeacherDao.class);
List<Student> allStu = mapper.getAllStu(1);
System.out.println(allStu.toString());
//更新
mapper.updateStu(1);
System.out.println("---------------------------");
List<Student> allStu2 = mapper.getAllStu(2);
System.out.println(allStu2.toString());
sqlSession.close();
}
4. 在两次查询期间,手动去清空缓存,也会让缓存失效,sqlSession.clearCache
@Test
public void testGetAllStu(){
TeacherDao mapper = sqlSession.getMapper(TeacherDao.class);
List<Student> allStu = mapper.getAllStu(1);
System.out.println(allStu.toString());
//手动清空缓存
sqlSession.clearCache();
System.out.println("---------------------------");
List<Student> allStu2 = mapper.getAllStu(2);
System.out.println(allStu2.toString());
sqlSession.close();
}
二级缓存
二级缓存是全局作用域缓存,默认是不开启的,需要手动进行配置。
Mybatis提供二级缓存的接口以及实现,缓存实现的时候要求实体类实现Serializable接口,二级缓存在sqlSession关闭或提交之后才会生效。
当添加上<cache/>标签之后,会有如下效果:
-
映射语句文件中的所有 select 语句的结果将会被缓存。
-
映射语句文件中的所有 insert、update 和 delete 语句会刷新缓存。
-
缓存会使用最近最少使用算法(LRU, Least Recently Used)算法来清除不需要的缓存。
-
缓存不会定时进行刷新(也就是说,没有刷新间隔)。
-
缓存会保存列表或对象(无论查询方法返回哪种)的 1024 个引用。
-
缓存会被视为读/写缓存,这意味着获取到的对象并不是共享的,可以安全地被调用者修改,而不干扰其他调用者或线程所做的潜在修改。
属性
<cache
eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
eviction:表示缓存回收策略,默认是LRU
LRU:最近最少使用的,移除最长时间不被使用的对象
FIFO:先进先出,按照对象进入缓存的顺序来移除
SOFT:软引用,移除基于垃圾回收器状态和软引用规则的对象
WEAK:弱引用,更积极地移除基于垃圾收集器状态和弱引用规则的对象
flushInternal:刷新间隔,单位毫秒,默认情况是不设置,也就是没有刷新间隔,缓存仅仅调用语句时刷新
size:引用数目,正整数,代表缓存最多可以存储多少个对象,太大容易导致内存溢出
readonly:只读,true/false
true:只读缓存,会给所有调用这返回缓存对象的相同实例,因此这些对象不能被修改。(因为返回的是同一个对象实例,当其中一次做了修改,那么缓存中的数据也会修改)
false:读写缓存,会返回缓存对象的拷贝(序列化实现),这种方式比较安全,默认值(返回的是对象的副本。)
三个条件:
1. 配置全局变量
<setting name="cacheEnabled" value="true"/>
2. 映射文件中.xml中配置 ,所以一个namespace对应一个二级缓存
<cache/>
3.实体类实现Serializable接口
使用
工作机制,
1. 一个会话,查询一条数据,这个数据就会被放在当前会话的一级缓存中;
2. 当sqlSession commit或者 close后,一级缓存中的数据会被保存到二级缓存中;
3. 新的会话查询信息,就可以参照二级缓存中的内容
查询顺序。二级缓存------一级缓存-------数据库。
先查询二级缓存,如果没有,则查询一级缓存,如果也没有去数据库查询
@Test
public void testGetAllStu(){
TeacherDao mapper = sqlSession.getMapper(TeacherDao.class);
//查询二级缓存,发现没有,查询一级缓存,也没有,查询数据库,并把结果放入一级缓存中
List<Student> allStu = mapper.getAllStu(1);
System.out.println(allStu.toString());
//查询二级缓存,发现没有,查询一级缓存,发现有,不去数据库查询
List<Student> allStu0 = mapper.getAllStu(1);
System.out.println(allStu0.toString());
//sqlSession关闭,将一级缓存中的数据放入二级缓存中
sqlSession.close();
System.out.println("---------------------------------------------");
//查询二级缓存,发现有,返回结果
TeacherDao mapper2 = sqlSession2.getMapper(TeacherDao.class);
List<Student> allStu2 = mapper2.getAllStu(1);
System.out.println(allStu2.toString());
//查询二级缓存,发现有,返回结果
List<Student> allStu3 = mapper2.getAllStu(1);
System.out.println(allStu3.toString());
System.out.println("-------------------------------------------------");
//查询二级缓存,发现没有,查询一级缓存,也没有,查询数据库,并把结果放入一级缓存中
List<Student> allStu4 = mapper2.getAllStu(2);
System.out.println(allStu4.toString());
//查询二级缓存,发现没有,查询一级缓存,发现有,不查询数据库
List<Student> allStu5 = mapper2.getAllStu(2);
System.out.println(allStu5);
//sqlSession2关闭,将一级缓存中的数据放入二级缓存中
sqlSession2.close();
}
打印结果
DEBUG [main] - Cache Hit Ratio [com.hww.dao.TeacherDao]: 0.0 //查询二级缓存 1次 ,命中0次,命中率 0.0
DEBUG [main] - ==> Preparing: select * from student where student_id =?
DEBUG [main] - ==> Parameters: 1(Integer)
TRACE [main] - <== Columns: student_id, teacher_id, name
TRACE [main] - <== Row: 1, 1, 东方不败
DEBUG [main] - <== Total: 1
[Student{studentId=1, teacherId=1, name='东方不败'}]
DEBUG [main] - Cache Hit Ratio [com.hww.dao.TeacherDao]: 0.0 //查询二级缓存 2次 ,命中0次,命中率 0.0
[Student{studentId=1, teacherId=1, name='东方不败'}]
---------------------------------------------
DEBUG [main] - Cache Hit Ratio [com.hww.dao.TeacherDao]: 0.3333333333333333 //查询二级缓存 3次 ,命中1次,命中率 1/3
[Student{studentId=1, teacherId=1, name='东方不败'}]
DEBUG [main] - Cache Hit Ratio [com.hww.dao.TeacherDao]: 0.5 //查询二级缓存 4次 ,命中2次,命中率 1/2
[Student{studentId=1, teacherId=1, name='东方不败'}]
-------------------------------------------------
DEBUG [main] - Cache Hit Ratio [com.hww.dao.TeacherDao]: 0.4 //查询二级缓存5次 ,命中2次,命中率 2/5
DEBUG [main] - ==> Preparing: select * from student where student_id =?
DEBUG [main] - ==> Parameters: 2(Integer)
TRACE [main] - <== Columns: student_id, teacher_id, name
TRACE [main] - <== Row: 2, 1, 西门吹雪
DEBUG [main] - <== Total: 1
[Student{studentId=2, teacherId=1, name='西门吹雪'}]
DEBUG [main] - Cache Hit Ratio [com.hww.dao.TeacherDao]: 0.3333333333333333 //查询二级缓存6次 ,命中2次,命中率 1/3
[Student{studentId=2, teacherId=1, name='西门吹雪'}]
根据比率可以看出确实是先查询二级缓存,在查询一级缓存,然后在查询数据库
缓存开启和清空
1.1)控制二级缓存的开启和关闭
<setting name="cacheEnabled" value="true"/>
cacheEnabled=true:开启缓存;false:关闭缓存(二级缓存关闭)(一级缓存一直可用的)
1.2)控制一级缓存的开启和关闭
<setting name="localCacheScope" value="SESSION"/>
localCacheScope:本地缓存作用域(一级缓存SESSION);
当前会话的所有数据保存在会话缓存中;STATEMENT:可以禁用一级缓存;
注意:一级缓存关闭后,二级缓存自然也无法使用;
1.3)每个sql语句也能控制缓存的开启和清空
每个select标签都默认配置了useCache="true":如果useCache= false:则表示不使用缓存(一级缓存依然使用,二级缓存不使用)
每个增删改标签默认配置了flushCache="true":(一级二级都会清除)
缓存的机制
一级缓存 Mybatis的一级缓存是指SQLSession,一级缓存的作用域是SQlSession, Mabits默认开启一级缓存。 在同一个SqlSession中,执行相同的SQL查询时;第一次会去查询数据库,并写在缓存中,第二次会直接从缓存中取。 当执行SQL时候两次查询中间发生了增删改的操作,则SQLSession的缓存会被清空。 每次查询会先去缓存中找,如果找不到,再去数据库查询,然后把结果写到缓存中。 Mybatis的内部缓存使用一个HashMap,key为hashcode+statementId+sql语句。Value为查询出来的结果集映射成的java对象。 SqlSession执行insert、update、delete等操作commit后会清空该SQLSession缓存。
2)二级缓存 二级缓存是mapper级别的,Mybatis默认是没有开启二级缓存的。 第一次调用mapper下的SQL去查询用户的信息,查询到的信息会存放代该mapper对应的二级缓存区域。 第二次调用namespace下的mapper映射文件中,相同的sql去查询用户信息,会去对应的二级缓存内取结果。
整合第三方缓存
在某些情况下我们也可以自定义实现缓存,或为其他第三方缓存方案创建适配器,来完全覆盖二级缓存行为。
这里使用ehcache 作为二级缓存
需要的jar包,其中mybatis-ehcache这个包是主要的,ehcache这个可以不用加入,因为mybatis-ehcache默认引入ehcache
还有两个日志包。
<!--第三方缓存-->
<!-- https://mvnrepository.com/artifact/org.ehcache/ehcache -->
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>3.8.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.2.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>2.0.0-alpha1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>2.0.0-alpha1</version>
<scope>test</scope>
</dependency>
ehcache.xml
需要引入一个配置文件ehcache.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">
<!-- 磁盘保存路径 -->
<diskStore path="D:\ehcache" />
<defaultCache
maxElementsInMemory="1"
maxElementsOnDisk="10000000"
eternal="false"
overflowToDisk="true"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
</defaultCache>
</ehcache>
<!--
属性说明:
l diskStore:指定数据在磁盘中的存储位置。
l defaultCache:当借助CacheManager.add("demoCache")创建Cache时,EhCache便会采用<defalutCache/>指定的的管理策略
以下属性是必须的:
l maxElementsInMemory - 在内存中缓存的element的最大数目
l maxElementsOnDisk - 在磁盘上缓存的element的最大数目,若是0表示无穷大
l eternal - 设定缓存的elements是否永远不过期。如果为true,则缓存的数据始终有效,如果为false那么还要根据timeToIdleSeconds,timeToLiveSeconds判断
l overflowToDisk - 设定当内存缓存溢出的时候是否将过期的element缓存到磁盘上
以下属性是可选的:
l timeToIdleSeconds - 当缓存在EhCache中的数据前后两次访问的时间超过timeToIdleSeconds的属性取值时,这些数据便会删除,默认值是0,也就是可闲置时间无穷大
l timeToLiveSeconds - 缓存element的有效生命期,默认是0.,也就是element存活时间无穷大
diskSpoolBufferSizeMB 这个参数设置DiskStore(磁盘缓存)的缓存区大小.默认是30MB.每个Cache都应该有自己的一个缓冲区.
l diskPersistent - 在VM重启的时候是否启用磁盘保存EhCache中的数据,默认是false。
l diskExpiryThreadIntervalSeconds - 磁盘缓存的清理线程运行间隔,默认是120秒。每个120s,相应的线程会进行一次EhCache中数据的清理工作
l memoryStoreEvictionPolicy - 当内存缓存达到最大,有新的element加入的时候, 移除缓存中element的策略。默认是LRU(最近最少使用),可选的有LFU(最不常使用)和FIFO(先进先出)
-->
配置ehcache缓存
在需要用ehcache的映射文件中配置以下配置。
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>