mybatis之缓存

为什么需要缓存

缓存是存在内存中的临时数据。我们查询数据库是耗资源的,一次查询结果给他暂存在一个可以直接存取到的地方,就是缓存,下次查询相同数据时,直接从缓存取,可以减少资源消耗。

什么数据可以使用缓存

经常查询并且不经常改变的数据

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>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lhj_loveFang_1105

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值