一. MyBatis 缓存
1、MyBatis 一级缓存
一级缓存是SqlSession级别的,通过同一个SqlSession查询的数据会被缓存,下次查询相同的数据,就会从缓存中直接获取,不会从数据重新访问
a. 一级缓存失效的四种情况:
- 1.1 不同的SqlSession对应不同的一级缓存
- 1.2 同一个SqlSession但是查询条件不同
- 1.3 同一个SqlSession两次查询期间执行了任何一次增删改操作
- 1.4 同一个SqlSession两次 查询期间手动清空了缓存:sqlSession.clearCache();
<!--Emp getEmpById(@Param("eid") Integer eid);-->
<select id="getEmpById" resultType="Emp">
select * from t_emp where eid = #{eid}
</select>
public void testCache() {
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
CacheMapper mapper = sqlSession.getMapper(CacheMapper.class);
Emp emp1 = mapper.getEmpById(1);
System.out.println(emp1);
Emp emp2 = mapper.getEmpById(1);
System.out.println(emp2); //SQL语句输出只有一条,证明是从缓存中获取的。
//重新输出一个条SQL语句,证明一级缓存范围只与sqlSession有关,和其他没有关系如mapper等
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
CacheMapper mapper2 = sqlSession.getMapper(CacheMapper.class);
Emp emp3 = mapper.getEmpById(1);
System.out.println(emp3);
}
2、MyBatis 二级缓存
二级缓存是SqlSessionFacotry级别,通过同一个SqlSessionFactory创建的SqlSession查询的结果会被缓存;此后若再次执行相同的查询语句,结果就会从缓存中获取
a. 二级缓存开启的条件
- 配置二级缓存:
-
- 在核心配置文件中,设置全局配置属性<setting name="cacheEnabled" value="true"/>,默认为true,不需要设置
-
- 在mapper映射文件中设置标签<cache type="org.mybatis.caches.ehcache.EhcacheCache" />
- 查询的数据所转换的实体类类型必须实现序列化的接口
- 手动开启二级缓存: 二级缓存必须在SqlSession关闭(close)或提交(commit)之后有效
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession1 = sqlSessionFactory.openSession(true);
CacheMapper cacheMapper1 = sqlSession1.getMapper(CacheMapper.class);
System.println(cacheMapper1.getEmpById(1));
sqlsession1.close();
SqlSession sqlSession2 = sqlSessionFactory.openSession(true);
CacheMapper cacheMapper2 = sqlSession1.getMapper(CacheMapper.class);
System.println(cacheMapper2.getEmpById(1));
sqlSession2.close();
b. 二级缓存失效的唯一情况
- 两次查询之间执行了任意的增删改,会使一级和二级缓存同时失效
c. 二级缓存的相关配置
在mapper配置文件中添加的cache标签可以设置的一些属性
- eviction 属性:缓存回收策略,默认LRU
-
- LRU(Least Recently Used) -最近最少使用的:移除最长时间不被使用的对象。
- FIFO(First in First out) -先进先出:按对象进入缓存的顺序来移除它们
- SOFT -软引用:移除基于垃圾回收器状态和软引用规则的对象
- WEAK -弱引用:更积极地移除基于垃圾收集器状态和弱引用规则的对象
- flushInterval 属性:刷新间隔,单位毫秒:默认情况是不设置,也就是没有刷新间隔,缓存仅仅调用增删改语句时刷新
- size 属性:引用数目,正整数:代表缓存最多可以存储多少个对象,太大容易导致内存溢出
- readOnly 属性:只读,true/flase
-
- true,只读缓存:会给所有调用者返回缓存对象的相同实例。因此这些对象不能被修改。这提供了很重要的性能优势。性能高,不安全
- false,读写缓存:会返回缓存对象的拷贝(通过序列化)。这会慢一些,但是安全,因此默认是false。安全,性能低
d. MyBatis 缓存查询的顺序
- 先查询二级缓存,因为二级缓存中可能会有其他程序已经查出来的数据,可以拿来直接使用。
- 如果二级缓存没有命中,再查一级缓存
- 如果一级缓存也没有命中,查询数据库
- SqlSession关闭后,一级缓存中数据会写入二级缓存
3、MyBatis 整合第三方缓存EHCache
通过第三方从内存读取数据(二级缓存)
a. 添加依赖
<!--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>
b. 创建EHCache的配置文件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="D:\lemon\ehcache" />
<defalultCache>
maxElementsInMemory="1000"
maxElementsOnDisk="10000000"
enternal="false"
overflowToDisk="true"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"
</defaultCache>
c. 在mapper.xml设置二级缓存的类型
<eache type="org.mybatis.caches.ehcache.EhcacheCache"/>
d. 加入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、REEOR-->
<!--指定打印日志的appender,这里通过“STDOUT”引用了前面配置的appender-->
<root level="DEBUG">
<!--指定打印日志的appender,这里通过“STDOUT”引用了前面配置的appender-->
<appender-ref ref="STDOUT" /
</root>
<!--根据特殊需求指定局部日志级别-->
<logger name="com.atguigu.crowd.mapper" level="DEBUG" />
</configuration>