13.缓存
13.1 简介
查询:连接数据库 ,耗资源
一次查询的结果,给他暂存到一个可以直接取到的地方 ! --> 内存:缓存
我们再次查询相同数据的时候,直接走缓存,就不用走数据库了
1.什么是缓存[cache]?
- 存在内存中的临时数据
- 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题
2.为什么使用缓存?
- 减少和数据库的交互次数,减少系统开销,提高系统效率
3.什么样的数据使用缓存
- 经常查询并且不经常改变的数据【可以使用缓存】
13.2 MyBatis缓存
- MyBatis 包含一个非常强大的查询缓存特性,它可以非常方便的定制和配置缓存。缓存可以极大地提高查询效率
- MyBatis系统中默认定义了两级缓存:一次缓存和二级缓存
- 默认情况下,只有一级缓存开启。(SQLSession级别的缓存,也称为本地缓存)
- 二级缓存需要手动开启和配置,它是基于namespace级别的缓存
- 为了提高扩展性, MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存
13.3 一级缓存
- 一级缓存也叫本地缓存,SQLSession级别的
- 与数据库同一次会话期间查询到的数据会放到本地缓存中
- 以后如果需要获得相同的数据,直接从缓存中拿,没必须再去查询数据库
实战:
mybatis-09
操作过程:
1)新建mybatis-09
2)拷贝resource下面的文件
3)pom文件中导入lombok
4)拷贝utils包,删除IDutils.java
5)在pojo下写User.java
6)在dao下写UserMapper.xml,UserMapper.java
手工写UserMapper.xml,
从mybatis-config.xml中拷贝内容,修改
删除标签体,!DocType后面的configuration改为mapper,config也改为mapper
测试步骤:
1.开启日志
2.测试在一个Session中查询两次相同的记录
3.查看日志输出
缓存失效的情况:
1.查询不同的东西
2.增删改操作,可能会改变原来的数据,所以必定会刷新缓存
3.查询不同的Mapper.xml
4.手动清理缓存
小结:
一级缓存默认是开启的,只在一次SQLSession中有效,也就是拿到连接到关闭连接这个区间段
一级缓存本质上就是一个Map
彩蛋
1.三高问题与缓存【没有什么是加一层加一层解决不了的-架构】
2.网站90%都是读操作(查询)
4.查看MyBatis的Cache接口,并看现有实现类
5.Debug 测试类观察一级缓存过程
6.一级缓存应用场景:
比如一个用户不停地刷新同一页面,这时就会用到一级缓存(有点牵强)
13.4 二级缓存
- 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
- 基于namespace级别的缓存,一个命名空间,对应一个二级缓存
- 工作机制
- 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中
- 如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中
- 新的会话查询信息,就可以从二级缓存中获取内容
- 不同的mapper查询出的数据会放在自己对应的缓存(map)中
步骤:
1.开启全局缓存
<!--显式的开启全局缓存-->
<setting name="cacheEnabled" value="true"/>
2.在要使用二级缓存的Mapper中开启
<!--在当前Mapper.xml中使用二级缓存-->
<cache/>
也可以自定义参数:
<!--在当前Mapper.xml中使用二级缓存-->
<cache eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
3.测试
1.问题:我们需要将实体类序列化,否则会出现如下报错:
org.apache.ibatis.cache.CacheException: Error serializing object. Cause: java.io.NotSerializableException: com.gongyi.pojo.User
小结:
- 只要开启了二级缓存,在同一个Mapper下就有效
- 所有的数据都会先放在一级缓存中
- 只有当会话提交,或者关闭的时候,才会提交到二级缓存中
13.5、缓存原理
13.6、自定义缓存- ehcache
Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存
要在程序中使用ehcache,要先导包
<!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.2.1</version>
</dependency>
在mapper中指定使用我们的ehcache缓存实现
ehcache.xml
目前用Redis数据库来做缓存 K-V
代码show
项目结构图:
pojo
package com.gongyi.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String pwd;
}
dao
package com.gongyi.dao;
import com.gongyi.pojo.User;
import org.apache.ibatis.annotations.Param;
public interface UserMapper {
//根据id查询用户
User queryUserById(@Param("id") int id);
int updateUser(User user);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.gongyi.dao.UserMapper">
<!--在当前Mapper.xml中使用二级缓存-->
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
<!--parameterType的值如果是基本类型,比如int,那么_int可以省略不写-->
<select id="queryUserById" parameterType="_int" resultType="user" useCache="true">
select * from mybatis.user where id = #{id}
</select>
<update id="updateUser" parameterType="user">
update mybatis.user set name = #{name},pwd=#{pwd} where id = #{id}
</update>
</mapper>
utils
package com.gongyi.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
//sqlSessionFactory -->sqlSession
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
//使用mybatis第一步:获取sqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = null;
inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession() {
return sqlSessionFactory.openSession(true);
}
}
resoures/db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8
username=root
password=123456
resoures/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"/>-->
<diskStore path="java.io.tmpdir/Tmp_EhCache"/>
<!--
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,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
-->
<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"/>
</ehcache>
resoures/mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--configuration核心配置文件-->
<configuration>
<!--引入外部配置文件-->
<properties resource="db.properties"/>
<settings>
<!--标准的日志工厂实现-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
<!--显式的开启全局缓存-->
<setting name="cacheEnabled" value="true"/>
</settings>
<!--可以给实体类起别名-->
<typeAliases>
<package name="com.gongyi.pojo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!--绑定接口-->
<mappers>
<mapper class="com.gongyi.dao.UserMapper"/>
</mappers>
</configuration>
test
import com.gongyi.dao.UserMapper;
import com.gongyi.pojo.User;
import com.gongyi.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
/**
* @Classname MyTest
* @Description TODO
* @Date 2021/12/31 8:36
* @Created by Administrator
*/
public class MyTest {
@Test
public void testFirstCache() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.queryUserById(1);
System.out.println(user);
System.out.println("===============");
User user2 = mapper.queryUserById(2);//观察console日志,分析一级缓存
System.out.println(user2);
System.out.println("==========");
//mapper.updateUser(new User(1,"new工一","new123456"));
//sqlSession.clearCache();//手动清理缓存
User user22 = mapper.queryUserById(2);
System.out.println(user22);
/* System.out.println(user == user2);
System.out.println("===============");
User user3 = mapper.queryUserById(1);
System.out.println(user3);
System.out.println(user3 == user);*/
sqlSession.close();
}
@Test
public void testSecondCache() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
SqlSession sqlSession1 = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.queryUserById(1);
System.out.println(user);
sqlSession.close();
UserMapper mapper1 = sqlSession1.getMapper(UserMapper.class);
User user1 = mapper1.queryUserById(1);
System.out.println(user1);
System.out.println(user==user1);
sqlSession1.close();
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>mybatis-study</artifactId>
<groupId>com.gy</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>mybatis-09</artifactId>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.2.1</version>
</dependency>
</dependencies>
</project>
彩蛋
1.ehcache.xml头部文件标红
alt+enter回车导入