为什么需要缓存
缓存是存在内存中的临时数据。我们查询数据库是耗资源的,一次查询结果给他暂存在一个可以直接存取到的地方,就是缓存,下次查询相同数据时,直接从缓存取,可以减少资源消耗。
什么数据可以使用缓存
经常查询并且不经常改变的数据
Mybatis缓存
·MyBatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存。缓存可以极大的提升查询效率。
- MyBatis系统中默认定义了两级缓存:一级缓存和二级缓存
- 默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)。二级缓存需要手动开启和配置,他是基于namespace级别的缓存。
- 为了提高扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存
一级缓存
开启日志搭建环境
package com.lei.dao;
import com.lei.pojo.User;
public interface UserMapper {
User findUserById(int id);
}
package com.lei.pojo;
public class User {
private int id;
private String name;
private String pwd;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}
<?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.lei.dao.UserMapper">
<select id="findUserById" parameterType="int" resultType="user">
select * from user where id = #{id}
</select>
</mapper>
@Test
public void findUserById() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User userById = mapper.findUserById(3);
System.out.println(userById);
System.out.println("===============================");
User userById2 = mapper.findUserById(3);
System.out.println(userById2);
System.out.println(userById == userById2);
sqlSession.close();
}

可以看到两次查询结果,是在一次SQLSession中完成的,第二次就是在缓存中查询的。
缓存失效
- 查询不同信息时
@Test
public void findUserById() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User userById = mapper.findUserById(3);
System.out.println(userById);
System.out.println("===============================");
User userById2 = mapper.findUserById(2);
System.out.println(userById2);
System.out.println(userById == userById2);
sqlSession.close();
}

- 中间有更新或者插入或者删除数据时,会刷新缓存
package com.lei.dao;
import com.lei.pojo.User;
public interface UserMapper {
User findUserById(int id);
int updateUser(User user);
}
<update id="updateUser" parameterType="user">
update user set name = #{name},pwd= #{pwd} where id = #{id}
</update>
@Test
public void findUserById() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User userById = mapper.findUserById(3);
System.out.println(userById);
mapper.updateUser(new User(2,"aaa","sass"));
System.out.println("===============================");
User userById2 = mapper.findUserById(3);
System.out.println(userById2);
System.out.println(userById == userById2);
sqlSession.close();
}

二级缓存
要启动二级缓存,需要在SQL映射文件中添加一行
<cache/>
就可以了。

也可以这样类似的修改属性。

开启二级缓存前提还得再核心配置文件里将这个字段设为true。

- 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存·基于namespace级别的缓存,一个名称空间,对应一个二级缓存。
- 工作机制
a.一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中;
b.如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中;
c.新的会话查询信息,就可以从二级缓存中获取内容;
d.不同的mapper查出的数据会放在自己对应的缓存(map)中;
测试
@Test
public void findUserById() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
SqlSession sqlSession2 = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
UserMapper mapper2 = sqlSession.getMapper(UserMapper.class);
User userById = mapper.findUserById(3);
System.out.println(userById);
sqlSession.close();
User userById2 = mapper2.findUserById(3);
System.out.println(userById2);
sqlSession2.close();
}

可以看出,分别在两个SQLSession中查询相同数据,就查了一次,二级缓存就触发了。
在这过程中可能会报这个错误:
org.apache.ibatis.cache.CacheException: Error serializing object
这时我们需要在对应的实体类实现序列化接口。
public class User implements Serializable
所有的数据都会先放在一级缓存中,只有当会话提交或者关闭时,才会转到二级缓存。
缓存顺序
- 先看二级缓存中有没有
- 再看一级缓存中有没有
- 都没有查询数据库
自定义缓存Ehcache
导包
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.1.0</version>
</dependency>
Mapper里配置
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
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 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"/>
</ehcache>
本文介绍了MyBatis的缓存机制。缓存可减少数据库查询的资源消耗,MyBatis默认有一级和二级缓存,一级缓存为SqlSession级别,二级缓存需手动开启,基于namespace级别。文中还阐述了缓存失效的情况、缓存顺序,最后介绍了自定义缓存Ehcache的方法。
1521

被折叠的 条评论
为什么被折叠?



