Mybatis十(缓存)

11 篇文章 0 订阅

Mybatis包含一个非常强大的查询缓存特性,他可以非常方便的配置和定制.缓存可以极大地提升查询效率.

Mybatis系统中默认定义了两级缓存. 
一级缓存个二级缓存.

    1. 默认情况下,只有一级缓存(sqlSession级别的缓存,也成为本地缓存)开启.
    1. 二级缓存需要手动开启和配置,他是基于namespace级别的缓存.
    1. 为了提高扩展性.mybatis定义了缓存接口Cache.我们可以通过实现Cache接口来自定投二级缓存.

一级缓存(本地缓存):sqlSession级别的缓存.一级缓存是一直开启的.

与数据库同一次会话区间查询到的数据放在本地缓存中.
以后如果需要获取相同的还是银行业,直接从缓存中拿,没必要再去查询数据库.

接口(EmployeeMapper.java)

/**
 * 测试一级缓存
 * @Author ZFH
 * @Date 2019年8月16日
 */
public Employee selEmployeeByid(Integer id);

配置文件(EmployeeMapper.xml)

<select id="selEmployeeByid" resultType="com.fish.pojo.Employee">
    select * from tbl_employee where id = #{id}
</select>

测试类

@org.junit.Test
public void test01() throws IOException {
    //读取配置文件
    InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
    //获取sqlsessionfactory
    SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
    //获取sqlsession
    SqlSession openSession = sessionFactory.openSession();
    //获取mapper对象
    EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);

    Employee selEmployeeByid = mapper.selEmployeeByid(1);
    System.out.println(selEmployeeByid);
    Employee selEmployeeByid2 = mapper.selEmployeeByid(1);
    System.out.println(selEmployeeByid2);
}

打印日志

==>  Preparing: select * from tbl_employee where id = ? 

==> Parameters: 1(Integer) 
<== Columns: id, last_name, gender, email, d_id 
<== Row: 1, 张三1, 1, ZFH_FISH@163.COM, 1 
<== Total: 1 
Employee [id=1, lastName=张三1, email=ZFH_FISH@163.COM, gender=1] 
Employee [id=1, lastName=张三1, email=ZFH_FISH@163.COM, gender=1]

结果: sql只执行了一遍,我们把两次查询条件换成不一样的,再执行一次.

打印日志

==>  Preparing: select * from tbl_employee where id = ? 

==> Parameters: 1(Integer) 
<== Columns: id, last_name, gender, email, d_id 
<== Row: 1, 张三1, 1, ZFH_FISH@163.COM, 1 
<== Total: 1 
Employee [id=1, lastName=张三1, email=ZFH_FISH@163.COM, gender=1] 
==> Preparing: select * from tbl_employee where id = ? 
==> Parameters: 2(Integer) 
<== Columns: id, last_name, gender, email, d_id 
<== Row: 2, 2, 1, 2, 2 
<== Total: 1 
Employee [id=2, lastName=2, email=2, gender=1]

结果: sql执行了两遍

一级缓存失效情况

没有使用到当前一级缓存的情况,效果就是:还需要再向数据库发出查询 
    1. sqlsession不同
    1. sqlsession相同,查询条件不同
    1. sqlsession相同,两次查询之间执行了增删改操作(本次增删改可能会影响当前数据)
    1. sqlsession相同,手动清除了一级缓存(openSession.clearCache())

二级缓存(全局缓存)

二级缓存是基于namespace级别的缓存,一个namespace对应一个二级缓存

工作机制

1. 一个会话查询一条数据,这个数据会被放在当前会话的一级缓存中.
3. 如果会话关闭,一级缓存中的数据就会被保存到二级缓存中;新的会话查询信息,就可以参照二级缓存中的内容;
3. 不同namespace查询出的数据会放在自己对应的缓存中(map)

注意:查询出来的数据默认都会放到一级缓存中.只有会话提交或者关闭后,一级缓存中的数据才会转移到二级缓存中

使用

    1. 开启全局二级缓存配置;()
    1. 去mapper.xml中配置使用二级缓存() 
      • eviction:缓存的回收策略: 
        LRU:最近最少使用的,移除最长时间不被使用的对象 
        • FIFO:先进先出,按对象进入缓存的顺序来移除他们
        • SOFT:软引用,移除基于垃圾回收器状态和软引用规则的对象
        • WEAK:弱引用,更积极的移除基于垃圾收集器状态和弱引用规则的对象
        • 默认是LRU
      • flushInterval:缓存刷新间隔
      • 缓存多长书剑清空依稀,默认不行清空,设置一个毫秒值
      • readOnly:是否只读
      • true:只读;mybatis认为所有从缓存中获取的数据的操作都是只读操作,不会修改数据,mybatis为了加快获取速度,直接就会将数据在缓存中的引用交给用户.不安全,速度快
      • false:非只读;mybatis觉得获取的数据Kenneth会被修改,mybatis会利用反序列化&序列化技术克隆一份新的数据给你.安全,速度慢
      • size:缓存存放多少元素
      • type:指定自定义环迅的全类名;实现Cache接口即可
    1. 我们的POJO需要实现序列化接口

缓存相关配置

    1. cacheEnable=true,false;关闭缓存(二级缓存关闭),一级缓存一直可用)
    1. 每个select标签都有useCache="true",false:不使用缓存(一级缓存依然使用,二级缓存不使用)
    1. 每个增删改标签的flushCache=true(一二级缓存都会清除) 
      • 增删改执行完成后就会清除缓存
      • flushCache=true;一二级缓存都会被清除
      • 查询标签:flushCache=false(默认);如果flushCache=true;每次查询后都会清空缓存;缓存是没有被使用的
    1. sqlSession.clearCache();只是清除当前Session的以及缓存
    1. localCacheScope:本地缓存作用域,(一级缓存) 
      • SESSION:当前hui会话的所有数据会保存在会话缓存中
      • STATEMENT:可以禁用掉一级缓存

Ehcache

好了 上面的了解一下就好了,下面介绍一个第三方缓存Ehcache

导jar包

相关jar包都可以在mybatis官网上找到

主配置文件(mybatis-config.xml)

 <!-- 开启日志  用户输出sql -->
<setting name="logImpl" value="STDOUT_LOGGING" />
<!-- 开启二级缓存 并使用第三方缓存 Ehcache -->
<setting name="cacheEnabled" value="true"></setting>

接口(EmployeeMapper.java)

public List<Employee> selEmpByNamesql(String lastName);

配置文件(EmployeeMapper.xml)

<cache type="org.mybatis.caches.ehcache.EhcacheCache"></cache>
<sql id="selColumn">
    id,last_name,gender,${email2}
</sql>
<select id="selEmpByNamesql" resultType="com.fish.pojo.Employee" useCache="true">
<bind name="_lastName" value="'%'+_parameter+'%'"/>
    select 
        <include refid="selColumn">
            <property name="email2" value="email"/>
        </include>
    from tbl_employee 
        <where>
             last_name like "%" #{_lastName} ""
        </where>
</select>
最重要的是cache标签 useCache每个select标签默认都是true可以不配置

ehcache.xml(想要ehcache生效,这个配置文件是必须的)

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../ehcache.org/ehcache.xsd">
<diskStore path="F:\ehcache" />
<defaultCache 
    maxElementsInMemory="1000" 
    maxElementsOnDisk="10000000"
    eternal="false" 
    overflowToDisk="false" 
    diskPersistent="true"
    timeToIdleSeconds="120"
    timeToLiveSeconds="120" 
    diskExpiryThreadIntervalSeconds="120"
    memoryStoreEvictionPolicy="LRU">
</defaultCache>


eternal="false" //是否永驻内存 
maxElementsInMemory="1000" //内存缓存中最多可以存放的元素 
maxElementsOnDisk="10000000"//磁盘中最多可以存放的元素 
overflowToDisk="false" //内存不足时是否缓存到磁盘 
diskPersistent="true"//是否持久化磁盘缓存 
timeToIdleSeconds="120"//失效前允许闲置时间,单位秒 
timeToLiveSeconds="120" //失效前允许存在时间,单位秒 
diskExpiryThreadIntervalSeconds="120"//磁盘缓存的清理线程运行间隔,默认是120秒。 
memoryStoreEvictionPolicy="LRU"//达到 maxElementsInMemory后的清理策略 

-->

测试类

Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@184cf7cf]
==>  Preparing: select id,last_name,gender,email from tbl_employee WHERE last_name like "%" ? "" 
==> Parameters: %四%(String)
<==    Columns: id, last_name, gender, email
<==        Row: 6, 李四, 1, zfh@163.com
<==        Row: 7, 李四2, 0, zfh@163.com
<==      Total: 2
[Employee [id=6, lastName=李四, email=zfh@163.com, gender=1], Employee [id=7, lastName=李四2, email=zfh@163.com, gender=0]]
Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@184cf7cf]
Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@184cf7cf]
Returned connection 407697359 to pool.
Cache Hit Ratio [com.fish.dao.EmployeeMapper]: 0.5
[Employee [id=6, lastName=李四, email=zfh@163.com, gender=1], Employee [id=7, lastName=李四2, email=zfh@163.com, gender=0]]

缓存到了本地磁盘

二级缓存原理图

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值