5. 缓存

5. 缓存

5.1.缓存-缓存介绍

MyBatis官方文档

MyBatis 包含一个非常强大的查询缓存特性,它可以非常方便地配置和定制。缓存可以极大的提升查询效率。

MyBatis系统中默认定义了两级缓存,一级缓存和二级缓存。

  1. 默认情况下,只有一级缓存( SqlSession级别的缓存,也称为本地缓存)开启。
  2. 二级缓存需要手动开启和配置,他是基于namespace级别的缓存。
  3. 为了提高扩展性。 MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存

5.2.缓存-一级缓存体验

一级缓存

  • 一级缓存(local cache),即本地缓存,作用域默认为sqlSession。当 Session flush 或 close 后, 该Session 中的所有 Cache 将被清空。
  • 本地缓存不能被关闭, 但可以调用 clearCache() 来清空本地缓存, 或者改变缓存的作用域.
  • 在mybatis3.1之后, 可以配置本地缓存的作用域. 在 mybatis.xml 中配置
- - - -
localCacheScope MyBatis uses local cache to prevent circular references and speed up repeated nested queries. By default (SESSION) all queries executed during a session are cached. If localCacheScope=STATEMENT local session will be used just for statement execution, no data will be shared between two different calls to the same SqlSession. SESSION/STATEMENT SESSION

一级缓存体验

CacheTest.java

public class CacheTest {
    
    

	@Test
	public void testFirstCache() throws IOException {
    
    
		SqlSessionFactory ssf = Tools.getSqlSessionFactory("c03/mybatis-config.xml");
		SqlSession session = ssf.openSession();
		
		try {
    
    
			EmployeeMapper em = session.getMapper(EmployeeMapper.class);
			
			Employee e1 = em.getEmpById(1);
			System.out.println(e1);
			
			Employee e2 = em.getEmpById(1);
			System.out.println(e2);
			
			System.out.println("e1 == e2 : " + (e1 == e2));
			
			session.commit();
		} finally {
    
    
			session.close();
		}
	}
}

输出结果:

DEBUG 08-02 22:50:35,092 ==>  Preparing: select * from employee where id = ?   (BaseJdbcLogger.java:145) 
DEBUG 08-02 22:50:35,192 ==> Parameters: 1(Integer)  (BaseJdbcLogger.java:145) 
DEBUG 08-02 22:50:35,260 <==      Total: 1  (BaseJdbcLogger.java:145) 
Employee [id=1, lastName=jallen2, [email protected], gender=1, department=null]
Employee [id=1, lastName=jallen2, [email protected], gender=1, department=null]
e1 == e2 : true <-------------e1和e2指向相同的对象

5.3.缓存-一级缓存失效的四种情况

同一次会话期间只要查询过的数据都会保存在当前SqlSession的一个Map中

  • key = hashCode + 查询的SqlId + 编写的sql查询语句 + 参数

一级缓存失效的四种情况:

  1. 不同的SqlSession对应不同的一级缓存
  2. 同一个SqlSession但是查询条件不同
  3. 同一个SqlSession两次查询期间执行了任何一次增删改操作
  4. 同一个SqlSession两次查询期间手动清空了缓存

5.4.缓存-二级缓存介绍

  • 二级缓存(second level cache),全局作用域缓存
  • 二级缓存默认不开启,需要手动配置
  • MyBatis提供二级缓存的接口以及实现,缓存实现要求 POJO实现Serializable接口
  • 二级缓存在 SqlSession 关闭或提交之后才会生效
  • 使用步骤
    1. 全局配置文件中开启二级缓存
      • <setting name="cacheEnabled" value="true"/>
    2. 需要使用二级缓存的映射文件处使用cache配置缓存
      • <cache />
    3. 注意: POJO需要实现Serializable接口

cache标签的属性:

  • eviction:缓存的回收策略:
    • LRU – 最近最少使用的:移除最长时间不被使用的对象。
    • FIFO – 先进先出:按对象进入缓存的顺序来移除它们。
    • SOFT – 软引用:移除基于垃圾回收器状态和软引用规则的对象。
    • WEAK – 弱引用:更积极地移除基于垃圾收集器状态和弱引用规则的对象。
    • 默认的是 LRU。
  • flushInterval:缓存刷新间隔
    • 缓存多长时间清空一次,默认不清空,设置一个毫秒值
  • readOnly:是否只读:
    • true:只读;mybatis认为所有从缓存中获取数据的操作都是只读操作,不会修改数据。mybatis为了加快获取速度,直接就会将数据在缓存中的引用交给用户。不安全,速度快
    • false:非只读:mybatis觉得获取的数据可能会被修改。mybatis会利用序列化&反序列的技术克隆一份新的数据给你。安全,速度慢
  • size:缓存存放多少元素;
  • type=“”:指定自定义缓存的全类名;
    • 实现Cache接口即可;

5.5.缓存-二级缓存使用&细节

使用步骤:

  1. 全局配置文件中开启二级缓存
    • <setting name="cacheEnabled" value="true"/>
  2. 需要使用二级缓存的映射文件处使用cache配置缓存
    • <cache />
  3. 注意: POJO需要实现Serializable接口

mybatis-config.xml

<configuration>
	<settings>
		<setting name="cacheEnabled" value="true"/>

Employee.java

public class Employee implements Serializable{
    
    

	private static final long serialVersionUID = -7390587151857533202L;


EmployeeMapper.xml

<mapper namespace="club.coderhome.c03.mapper.dao.EmployeeMapper">

	<cache eviction="FIFO" flushInterval="60000" readOnly="false" size="1024"></cache>

CacheTest.java

public class CacheTest {
    
    

	@Test
	public void testSecondCache() throws IOException {
    
    
		SqlSessionFactory ssf = Tools.getSqlSessionFactory("c05/mybatis-config.xml");
		SqlSession session = ssf.openSession();
		SqlSession session2 = ssf.openSession();
		
		try {
    
    
			EmployeeMapper em = session.getMapper(EmployeeMapper.class);
			Employee e1 = em.getEmpById(1);
			System.out.println(e1);
			session.close();
			
			EmployeeMapper em2 = session2.getMapper(EmployeeMapper.class);
			Employee e2 = em2.getEmpById(1);
			System.out.println(e2);
			
			System.out.println("e1 == e2 : " + (e1 == e2));
			
		} finally {
    
    
			session2.close();
		}
	}

输出结果:

DEBUG 08-03 01:13:02,575 Cache Hit Ratio [club.coderhome.c03.mapper.dao.EmployeeMapper]: 0.0  (LoggingCache.java:62) 
DEBUG 08-03 01:13:03,945 ==>  Preparing: select * from employee where id = ?   (BaseJdbcLogger.java:145) 
DEBUG 08-03 01:13:04,081 ==> Parameters: 1(Integer)  (BaseJdbcLogger.java:145) 
DEBUG 08-03 01:13:04,186 <==      Total: 1  (BaseJdbcLogger.java:145) 
Employee [id=1, lastName=jallen2, [email protected], gender=1, department=null]
DEBUG 08-03 01:13:04,218 Cache Hit Ratio [club.coderhome.c03.mapper.dao.EmployeeMapper]: 0.5  (LoggingCache.java:62) 
Employee [id=1, lastName=jallen2, [email protected], gender=1, department=null]
e1 == e2 : false

5.6.缓存-缓存有关的设置以及属性

  1. 全局setting的cacheEnable:
    – 配置二级缓存的开关。一级缓存一直是打开的。
  2. select标签的useCache属性:
    – 配置这个select是否使用二级缓存。一级缓存一直是使用的
  3. 每个增删改标签的flushCache属性:
    – 增删改默认flushCache=true。sql执行以后,会同时清空一级和二级缓存。查询默认flushCache=false。
  4. sqlSession.clearCache():
    – 只是用来清除一级缓存。
  5. 全局setting的localCacheScope:本地缓存作用域:(一级缓存SESSION),当前会话的所有数据保存在会话缓存中;STATEMENT:可以禁用一级缓存。

5.7.缓存-缓存原理图示

img

5.8.缓存-第三方缓存整合原理&ehcache适配包下载

  • EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。
  • MyBatis定义了Cache接口方便我们进行自定义扩展。
package org.apache.ibatis.cache;

import java.util.concurrent.locks.ReadWriteLock;

public interface Cache {
    
    

  String getId();

  void putObject(Object key, Object value);

  Object getObject(Object key);

  Object removeObject(Object key);

  void clear();

  int getSize();
  
  ReadWriteLock getReadWriteLock();

}

5.9.缓存-MyBatis整合ehcache&总结

步骤:

  • 加入mybatis-ehcache依赖
<dependency>
    <groupId>org.mybatis.caches</groupId>
    <artifactId>mybatis-ehcache</artifactId>
    <version>1.2.1</version>
</dependency>

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
 <!-- 磁盘保存路径 -->
 <diskStore path="C:\\ehcache" />
 
 <defaultCache 
   maxElementsInMemory="10000" 
   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(先进先出)
 -->
  • 配置cache标签<cache type="org.mybatis.caches.ehcache.EhcacheCache"></cache>

演示:

DepartmentMapper.xml

<mapper namespace="club.coderhome.c03.mapper.dao.DepartmentMapper">
	
	<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
	

CacheTest.java

public class CacheTest {
    
    

	@Test
	public void testEhcache() throws IOException {
    
    
		SqlSessionFactory ssf = Tools.getSqlSessionFactory("c05/mybatis-config.xml");
		SqlSession session = ssf.openSession();
		SqlSession session2 = ssf.openSession();
		
		try {
    
    
			DepartmentMapper dm = session.getMapper(DepartmentMapper.class);
			Department dp = dm.getDeptById(1);
			System.out.println(dp);
			session.close();
			
			DepartmentMapper dm2 = session2.getMapper(DepartmentMapper.class);
			Department dp2 = dm2.getDeptById(1);
			System.out.println(dp2);
			
		} finally {
    
    
			session2.close();
		}
	}

另外

参照缓存: 若想在命名空间中共享相同的缓存配置和实例。可以使用 cache-ref 元素来引用另外一个缓存。

<mapper namespace="club.coderhome.mybatis.dao.DepartmentMapper">
	<!-- 引用缓存:namespace:指定和哪个名称空间下的缓存一样 -->
	<cache-ref namespace="club.coderhome.mybatis.dao.EmployeeMapper"/>

猜你喜欢

转载自blog.csdn.net/qq_29216579/article/details/130986200