11.缓存
11.1简介
问题:
查询:连接数据库,耗费资源。
一次查询的结果,给他暂存在一个可以直接取到的地方——内存:缓存
我们再次查询相同数据的时候,直接走缓存,就不用走数据库了。
1.什么是缓存?
- 存在内存中的临时数据
- 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题。
2.为什么使用缓存?
- 减少和数据库的交互次数,减少系统开销,提高系统效率。
3.什么样的数据能使用缓存
- 经常查询并且不经常改变的数据
- 不经常查询 or 经常改变的数据不使用缓存
11.2Mybatis缓存
-
MyBatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存。缓存可以极大的提升查询效率。
-
MyBatis系统中默认定义了两级缓存:一级缓存和二级缓存
- 默认情况下,只有一级缓存开启(SQLSession级别的缓存,也称本地缓存,作用域从SQLSession开启到结束
- 二级缓存需要手动配置和开启,它是基于namespace级别的缓存(在一个Mapper中有效,也称全局缓存;查询数据库,数据存入一级缓存,当SQLSession关闭时,将其缓存交付给二级缓存)
- MyBatis自定义了缓存接口Cache,可以自定义二级缓存
- 缓存清除策略:
11.3一级缓存
- 一级缓存也叫本地缓存,SqlSession级别,从SqlSession开始到关闭期间
- 与数据库同一次会话期间查询到的数据会放在本地缓存中
- 这期间需要获取相同的数据,直接从缓存中拿,没必要再去查询数据库;
- 一级缓存自动开启
1.测试
在同一SqlSession中查询两次相同记录
-
开启日志
-
测试代码:
Mapper接口:
//根据id查询用户
User queryUserbyId(@Param("id") int id);
Mapper.xml:
<select id="queryUserbyId" resultType="com.kuang.pojo.User">
select * from `user` where id=#{id};
</select>
test:
public void testQueryUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user1 =mapper.queryUserbyId(1);
System.out.println(user1);
System.out.println("===========同一个SqlSession中两次查询相同记录================");
User user2 =mapper.queryUserbyId(1);
System.out.println(user2);
System.out.println("user1==user2:"+(user1==user2));
sqlSession.close();
}
-
测试结果:
2.一级缓存失效
SqlSession一级缓存失效的情况
(1)SqlSession不同
public void testQueryUserById(){
SqlSession sqlSession1 = MybatisUtils.getSqlSession();
SqlSession sqlSession2 = MybatisUtils.getSqlSession();
//第一次查询
UserMapper mapper1 = sqlSession1.getMapper(UserMapper.class);
User user1 =mapper1.queryUserbyId(1);
System.out.println(user1);
System.out.println("===========Sqlsession不同================");
//第二次查询
UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class);
User user2 =mapper2.queryUserbyId(1);
System.out.println(user2);
sqlSession1.close();
sqlSession2.close();
}
观察结果:两次查询都查询了数据库;
结论:每个SqlSession中缓存相互独立
(2)SqlSession相同,查询条件不同
public void testQueryUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user1 =mapper.queryUserbyId(1);
System.out.println(user1);
System.out.println("===========SqlSession相同,查询条件不同================");
User user2 =mapper.queryUserbyId(2);
System.out.println(user2);
System.out.println("user1==user2:"+(user1==user2));
sqlSession.close();
}
(3)增删改操作,可能会改变原来的数据,所以必定会刷新缓存
增删改之后,再次查询,会重新查询数据库;
//第一次查询
User user1 =mapper.queryUserbyId(1);
System.out.println(user1);
System.out.println("===========增删改操作,会刷新缓存================");
//更新
Map<String,Object> map=new HashMap<String, Object>();
map.put("id",1);
map.put("name","zhangsan2");
map.put("pwd","zhang123321");
mapper.updateUser(map);
//第二次查询
User user2 =mapper.queryUserbyId(1);
System.out.println(user2);
(4)SqlSession相同,手动清除一级缓存
第二次查询会重新查询数据库
public void testQueryUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
//第一次查询
UserMapper mapper1 = sqlSession.getMapper(UserMapper.class);
User user1 =mapper1.queryUserbyId(1);
System.out.println(user1);
System.out.println("===========手动清除以及缓存================");
//手动清除以及缓存
sqlSession.clearCache();
//第二次查询
UserMapper mapper2 = sqlSession.getMapper(UserMapper.class);
User user2 =mapper2.queryUserbyId(1);
System.out.println(user2);
sqlSession.close();
}
一级缓存就是一个Map,key-value键值对
11.4二级缓存
-
二级缓存也叫全局缓存,一级缓存作用域只在一个SqlSession内,作用于太低,所以诞生了二级缓存
-
基于namespace级别的缓存,一个命名空间,对应一个二级缓存
-
工作机制:
- 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中;
- 如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存的数据被保存到二级缓存中;
- 新的会话查询信息,就可以从二级缓存中获取内容;
- 不同的mapper查出的数据会放在自己对应的缓存(map)中
使用步骤
1.在mybatis-config.xml核心配置文件中,开启全局缓存
<!--显式的开启全局缓存-->
<setting name="cacheEnabled" value="true"/>
2.在要使用二级缓存的Mapper.xml中开启
<cache/>
也可以自定义参数
<cache
eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
3.测试
(1)遇到问题:实体类需要序列化,否则就会报错
Cause: java.io.NotSerializableException: com.kuang.pojo.User
解决:
public class User implements Serializable {......}
(2)两个SqlSession测试二级缓存:
public void testQueryUserById(){
//第一次查询
SqlSession sqlSession1 = MybatisUtils.getSqlSession();
UserMapper mapper1 = sqlSession1.getMapper(UserMapper.class);
User user1 =mapper1.queryUserbyId(1);
System.out.println(user1);
sqlSession1.close();
System.out.println("===========两个SqlSession测试二级缓存================");
//第二次查询
SqlSession sqlSession2 = MybatisUtils.getSqlSession();
UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class);
User user2 =mapper2.queryUserbyId(1);
System.out.println(user2);
sqlSession2.close();
}
小结
- 只要开启了二级缓存,在同一个Mapper下就有效
- 所有的数据都会先放在一级缓存中
- 只有当会话提交或者关闭时,才会提交到二级缓存中
11.5缓存原理
采用缓存后,查询数据先后顺序:
1.先看二级缓存中有没有
2.再看二级缓存中有没有
3.都没有查询数据库
11.6自定义缓存ehcache
- ehcache是第三方缓存,是一个纯Java的进程内缓存框架
- 是一种广泛使用的java分布式缓存,用于通用缓存
1.使用需要导入jar包
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.2.1</version>
</dependency>
2.在mapper.xml中使用对应的缓存即可
<mapper namespace="com.kuang.dao.UserMapper">
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
</mapper>
3.编写ehcache.xml配置文件,放在resources中;如果在加载时未找到/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"
updateCheck="false">
<!--
diskStore:为缓存路径,ehcache分为内存和磁盘两级,此属性定义磁盘的缓存位置。参数解释如下:
user.home – 用户主目录
user.dir – 用户当前工作目录
java.io.tmpdir – 默认临时文件路径
-->
<diskStore path="./tmpdir/Tmp_EhCache"/>
<defaultCache
eternal="false"
maxElementsInMemory="10000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="259200"
memoryStoreEvictionPolicy="LRU"/>
<cache
name="cloud_user"
eternal="false"
maxElementsInMemory="5000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="1800"
memoryStoreEvictionPolicy="LRU"/>
<!--
defaultCache:默认缓存策略,当ehcache找不到定义的缓存时,则使用这个缓存策略。只能定义一个。
-->
<!--
name:缓存名称。
maxElementsInMemory:缓存最大数目
maxElementsOnDisk:硬盘最大缓存个数。
eternal:对象是否永久有效,一但设置了,timeout将不起作用。
overflowToDisk:是否保存到磁盘,当系统当机时
timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
clearOnFlush:内存数量最大时是否清除。
memoryStoreEvictionPolicy:可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。
FIFO,first in first out,这个是大家最熟的,先进先出。
LFU, Less Frequently Used,就是上面例子中使用的策略,直白一点就是讲一直以来最少被使用的。如上面所讲,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。
LRU,Least Recently Used,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
-->
</ehcache>
Mybatis缓存使用不多,大多被Redis缓存数据库,key-value键值对。
12.错误
【错误1】测试类不要和Mapper接口同名,测试类的测试函数不要和Mapper中接口函数同名
否则会出现找不到java方法
或者找到测试类的测试函数,但是传递方法参数不对
【错误2】
Cause: com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceExcep
解决方法:之前在pom.xml文件中删除了下面代码,现在加上:
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
【错误3】
新建Mapper接口时不要建成了类