Mybatis缓存+懒加载概念

一级缓存:

一级缓存是sqlsession级别的缓存,会话一结束缓存就被刷新清空

  • 在操作数据库时,需要构造sqlsession对象,在对象中有一个数据结构(HashMap)用于存储缓存数据
  • 不同的sqlsession之间的缓存区域是互相不影响的。
    在这里插入图片描述
  • 第一次发起查询sql查询用户id为1的用户,先去找缓存中是否有id为1的用户,如果没有,再去数据库查询用户信息。得到用户信息,将用户信息存储到一级缓存中。
  • 如果sqlsession执行了commit操作(插入,更新,删除),会清空sqlsession中的一级缓存,避免脏读
  • 第二次发起查询id为1的用户,缓存中如果找到了,直接从缓存中获取用户信息
  • mybatis默认支持并开启一级缓存。

★★数据不一致问题:

如果增删改操作不清空缓存,事务一把mysql的数据改了,事务二来查,直接查到缓存数据,而缓存数据未被事务一修改,事务二查到的数据和事务一不一致。

一级缓存演示:

1、必须配置日志,要不看不见
2、编写接口方法

//根据id查询用户
User findUserById(@Param("id") int id);

3、接口对应的Mapper文件

<select id="findUserById" resultType="com.xinzhi.entity.User">
  select * from user where id = #{id}
</select>

4、测试

@Test
public void testFindUserById(){
    UserMapper mapper = session.getMapper(UserMapper.class);
    User user1 = mapper.findUserById(1);
    System.out.println(user1);
    User user2 = mapper.findUserById(3);
    System.out.println(user2);
    User user3 = mapper.findUserById(1);
    System.out.println(user3);
}

5、通过日志分析

[com.xinzhi.dao.UserMapper.findUserById]-==>  Preparing: select id,username,password from user where id = ? 
[com.xinzhi.dao.UserMapper.findUserById]-==> Parameters: 1(Integer)
[com.xinzhi.dao.UserMapper.findUserById]-<==      Total: 1
User{id=1, username='楠哥', password='123456'}         ---->ID为1,第一次有sql
[com.xinzhi.dao.UserMapper.findUserById]-==>  Preparing: select id,username,password from user where id = ? 
[com.xinzhi.dao.UserMapper.findUserById]-==> Parameters: 3(Integer)
[com.xinzhi.dao.UserMapper.findUserById]-<==      Total: 1
User{id=3, username='磊哥', password='987654'}         ---->ID为3,第一次有sql
User{id=1, username='楠哥', password='123456'}         ---->ID为1,第二次无sql,走缓存

一级缓存失效

  1. sqlSession不同
  2. 当sqlSession对象相同的时候,查询的条件不同,,原因是第一次查询时候一级缓存中没有第二次查询所需要的数据
  3. 当sqlSession对象相同,两次查询之间进行了插入的操作
  4. 当sqlSession对象相同,手动清除了一级缓存中的数据

二级缓存(面向不经常发生改变的数据,较少用):

会话提交之后,一级缓存内容会保存在二级缓存中。

二级缓存是mapper(namespace)级别的缓存

  • 多个sqlsession去操作同一个mapper的sql语句,多个sqlsession可以共用二级缓存,所得到的数据会存在二级缓存区域,
  • 二级缓存是跨sqlsession的
  • 二级缓存相比一级缓存的范围更大(按namespace来划分),多个sqlsession可以共享一个二级缓存

在这里插入图片描述

首先要手动开启mybatis二级缓存:

在config.xml设置二级缓存开关 , 还要在具体的mapper.xml开启二级缓存

<settings>
    <!--开启二级缓存-->
    <setting name="cacheEnabled" value="true"/>       
</settings>
<!-- 需要将映射的javabean类实现序列化 -->
class Student implements Serializable{}
<!--开启本Mapper的namespace下的二级缓存-->
<cache eviction="LRU" flushInterval="100000"/>
(1)cache属性的简介:

eviction回收策略(缓存满了的淘汰机制),目前MyBatis提供以下策略:

  1. LRU(Least Recently Used),最近最少使用的,最长时间不用的对象
  2. FIFO(First In First Out),先进先出,按对象进入缓存的顺序来移除他们
  3. SOFT,软引用,移除基于垃圾回收器状态和软引用规则的对象
  4. WEAK,弱引用,更积极的移除基于垃圾收集器状态和弱引用规则的对象。这里采用的是LRU,
    移除最长时间不用的对形象

flushInterval:刷新间隔时间,单位为毫秒,

  1. 这里配置的是100秒刷新,如果你不配置它,那么当SQL被执行的时候才会去刷新缓存。
    如果表数据经常变动,时间可以设置短一些

size:引用数目,

  1. 一个正整数,代表缓存最多可以存储多少个对象,不宜设置过大。设置过大会导致内存溢出。
    这里配置的是1024个对象

**readOnly:**只读,

  1. 意味着缓存数据只能读取而不能修改,这样设置的好处是我们可以快速读取缓存,缺点是我们没有
    办法修改缓存,他的默认值是false,不允许我们修改
2)操作过程:

sqlsession1查询用户id为1的信息,查询到之后,会将查询数据存储到二级缓存中。
如果sqlsession3去执行相同mapper下sql,执行commit提交,会清空该mapper下的二级缓存区域的数据
sqlsession2查询用户id为1的信息, 去缓存找 是否存在缓存,如果存在直接从缓存中取数据

禁用二级缓存:
在statement中可以设置useCache=false,禁用当前select语句的二级缓存,默认情况为true

<select id="getStudentById" parameterType="java.lang.Integer" resultType="Student" useCache="false">

在实际开发中,针对每次查询都需要最新的数据sql,要设置为useCache=“false” ,禁用二级缓存

flushCache标签:刷新缓存(清空缓存):

<select id="getStudentById" parameterType="java.lang.Integer" resultType="Student" flushCache="true">

一般下执行完commit操作都需要刷新缓存,flushCache="true 表示刷新缓存,可以避免脏读

二级缓存应用场景:

对于访问多的查询请求并且用户对查询结果实时性要求不高的情况下,可采用mybatis二级缓存,降低数据库访问量,提高访问速度,如电话账单查询
根据需求设置相应的flushInterval:刷新间隔时间,比如三十分钟,24小时等。

二级缓存局限性:

mybatis二级缓存对细粒度的数据级别的缓存实现不好,比如如下需求:对商品信息进行缓存,由于商品信息查询访问量大,但是要求用户每次都能查询最新的商品信息,此时如果使用mybatis的二级缓存就无法实现当一个商品变化时只刷新该商品的缓存信息而不刷新其它商品的信息,因为mybaits的二级缓存区域以mapper为单位划分,当一个商品信息变化会将所有商品信息的缓存数据全部清空。解决此类问题需要在业务层根据需求对数据有针对性缓存。

二级缓存演示:

先不进行配置:

@Test
public void testFindUserCache() throws Exception {

    //使用不同的mapper
    UserMapper mapper1 = session.getMapper(UserMapper.class);
    User user1 = mapper1.findUserById(1);
    System.out.println(user1);
    //提交了就会刷到二级缓存,要不还在一级缓存,一定要注意
    session.commit();
    UserMapper mapper2 = session.getMapper(UserMapper.class);
    User user2 = mapper2.findUserById(1);
    System.out.println(user2);
    System.out.println(user1 == user2);
}

结果:

[com.xinzhi.dao.UserMapper.findUserById]-==>  Preparing: select id,username,password from user where id = ? 
[com.xinzhi.dao.UserMapper.findUserById]-==> Parameters: 1(Integer)
[com.xinzhi.dao.UserMapper.findUserById]-<==      Total: 1
User{id=1, username='楠哥', password='123456'}
[com.xinzhi.dao.UserMapper.findUserById]-==>  Preparing: select id,username,password from user where id = ? 
[com.xinzhi.dao.UserMapper.findUserById]-==> Parameters: 1(Integer)
[com.xinzhi.dao.UserMapper.findUserById]-<==      Total: 1
User{id=1, username='楠哥', password='123456'}
false               ---->两个对象不是一个,发了两个sql,说明缓存没有起作用

可以看见两次同样的sql,却都进库进行了查询。说明二级缓存没开。

配置二级缓存:

1、开启全局缓存

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

2、使用二级缓存,这个写在mapper里

<!--开启本Mapper的namespace下的二级缓存-->
<cache eviction="LRU" flushInterval="100000" size="512" readOnly="true"></cache>
<!--
创建了一个 LRU 最少使用清除缓存,每隔 100 秒刷新,最多可以存储 512 个对象,返回的对象是只读的。
-->

3、测试执行

[com.xinzhi.dao.UserMapper.findUserById]-==>  Preparing: select id,username,password from user where id = ? 
[com.xinzhi.dao.UserMapper.findUserById]-==> Parameters: 1(Integer)
[com.xinzhi.dao.UserMapper.findUserById]-<==      Total: 1
User{id=1, username='楠哥', password='123456'}
[com.xinzhi.dao.UserMapper]-Cache Hit Ratio [com.xinzhi.dao.UserMapper]: 0.5
User{id=1, username='楠哥', password='123456'}
true                  ---->两个对象一样了,就发了一个sql,说明缓存起了作用

第三方缓存–EhCache充当三级缓存

我们的三方缓存组件很对,最常用的比如ehcache,Memcached、redis等,我们以比较简单的ehcache为例。

1、引入依赖

<!-- 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>

2、修改mapper.xml中使用对应的缓存

<mapper namespace = “com.xinzhi.entity.User” > 
       <cache type="org.mybatis.caches.ehcache.EhcacheCache" eviction="LRU" flushInterval="10000" size="1024" readOnly="true"/>
</mapper>

3、添加ehcache.xml文件,ehcache配置文件,具体配置自行百度

<?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"/>

</ehcache>

<!--     
       name:缓存名称。     
       maxElementsInMemory:缓存最大个数。     
       eternal:对象是否永久有效,一但设置了,timeout将不起作用。     
       timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。     
       timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。     
       overflowToDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。     
       diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。     
       maxElementsOnDisk:硬盘最大缓存个数。     
       diskPersistent:是否在磁盘上持久化。指重启jvm后,数据是否有效。默认为false。   
       memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。     
       clearOnFlush:内存数量最大时是否清除。     
    --> 

3、测试

[com.xinzhi.dao.UserMapper.findUserById]-==>  Preparing: select id,username,password from user where id = ? 
[com.xinzhi.dao.UserMapper.findUserById]-==> Parameters: 1(Integer)
[com.xinzhi.dao.UserMapper.findUserById]-<==      Total: 1
User{id=1, username='楠哥', password='123456'}
[com.xinzhi.dao.UserMapper]-Cache Hit Ratio [com.xinzhi.dao.UserMapper]: 0.5
User{id=1, username='楠哥', password='123456'}
true

4、使用缓存独立控制

其实我们更加常见的是使用第三方的缓存进行存储,并且自由控制

<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <version>2.10.3</version>
</dependency>  

测试一下

final CacheManager cacheManager = new CacheManager(this.getClass().getClassLoader().getResourceAsStream("ehcache.xml"));

// create the cache called "hello-world"
String[] cacheNames = cacheManager.getCacheNames();
for (String cacheName : cacheNames) {
    System.out.println(cacheName);
}
Cache userDao = cacheManager.getCache("userDao");
Element element = new Element("testFindUserById_1",new User(1,"q","d"));
userDao.put(element);

Element element1 = userDao.get("testFindUserById_1");
User user = (User)element1.getObjectValue();
System.out.println(user);

创建工具类

/**
 * @author zn
 * @date 2021/1/28
 */
public class CacheUtil {

    private static CacheManager cacheManager = new CacheManager(CacheUtil.class.getClassLoader().getResourceAsStream("ehcache.xml"));

    public static void put(String cacheName,String key,Object value){
        Cache cache = cacheManager.getCache(cacheName);
        Element element = new Element(key,value);
        cache.put(element);
    }

    public static Object get(String cacheName,String key){
        Cache cache = cacheManager.getCache(cacheName);
        return cache.get(key).getObjectValue();

    }

    public static boolean  delete(String cacheName,String key){
        Cache cache = cacheManager.getCache(cacheName);
        return cache.remove(key);
    }

}

测试

@Test
    public void selectDeptsTest(){

        Map<String,Object> cache = new HashMap<>(8);
        // 执行方法
        List<Dept> depts = deptMapper.selectDepts();
        CacheUtil.put("dept","selectUserByIdTest",depts);
        System.out.println(depts);
        session.commit();

        session = sqlSessionFactory.openSession();
        // 去缓存拿,如果有就拿出来
        List<Dept> newDepts = null;
        Object object = CacheUtil.get("dept", "selectUserByIdTest");
        if(object == null){
            // 去数据库查询
            DeptMapper mapper = session.getMapper(DeptMapper.class);
            newDepts = mapper.selectDepts();
        } else {
            newDepts = (List<Dept>) object;
        }

        System.out.println(newDepts);
    }

懒加载:

没有真正用到执行sql语句的方法时,不执行sql语句,真正用了才执行。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值