查询: 连接数据库,耗资源!
一次查询的结果,给他暂存在一个可以直接取到的地方!--->内存 : 缓存
我们再次查询相同数据的时候,直接走缓存,就不用走数据库了!
1.什么是缓存[ Cache ]?
mybatis默认缓存为LRU算法,数据时间最长,就会被清除
测试步骤:
1.开启日志
2.测试在一个Session中查询两次相同记录
3.查看日志输出
步骤:
1.开启全局缓存
<!--显示的开启全局缓存-->
<setting name="cacheEnabled" value="true"/>
2.要使用二级缓存的Mapper中开启
<!--在当前Mapper.xml中使用二级缓存默认是LRU算法-->
<cache/>
也可以自定义参数
<!--在当前Mapper.xml中使用二级缓存-->
<cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>
3.测试
问题:我们需要将实体类序列化!否则就会报错
小结:
一级缓存是默认的,二级缓存需要开启,范围在namespace内。一级缓存只在链接SqlSession中有效,链接关闭后会失效。二级缓存触发事务后会自动失效。
Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存,Java EE和轻量级容器。
如何使用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中使用二级缓存-->
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
3.创建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 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>
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/m0_51067047/article/details/118096032
内容来源于网络,如有侵权,请联系作者删除!