第十三章、缓存
查询: 链接数据库 耗资源
一次查询的结果给他暂存在一个可以直接取到的地方---->内存 :缓存
再次查询相同的数据,直接走缓存,不需要走数据库
一级缓存

只创建了一次sqlsession,第二次从缓存中取
缓存失效
-
查询不同的东西
-
增删改操作,可能会改变原来的数据

-
查询不同的Mapper.xml
-
手动清理缓存

小结:一级缓存默认是开启的,只在一次SqlSession中有效,也就是拿到链接到关闭链接这个区间段
二级缓存
-
开启缓存
1 <setting name="cacheEnabled" value="true"/>
-
在mapper中开启
1 <cache 2 eviction="FIFO" 3 flushInterval="60000" 4 size="512" 5 readOnly="true"/> 6
问题:
-
我们需要将实体类序列化
1 Cause: java.io.NotSerializableException: com.pojo.User
小结:
-
只要开启了二级缓存,在同一个Mapper下就有效
-
所有的数据都会先放在一级缓存中
-
只有当会话提交,或者关闭的时候,才会提交到二级缓存中

自定义缓存 ehcache
1 <!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache --> 2 <dependency> 3 <groupId>org.mybatis.caches</groupId> 4 <artifactId>mybatis-ehcache</artifactId> 5 <version>1.1.0</version> 6 </dependency>
1 <?xml version="1.0" encoding="UTF-8"?> 2 <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd" 4 updateCheck="false"> 5 6 <diskStore path="./tmpdir/Tmp_EhCache"/> 7 8 <defaultCache 9 eternal="false" 10 maxElementsInMemory="10000" 11 overflowToDisk="false" 12 diskPersistent="false" 13 timeToIdleSeconds="1800" 14 timeToLiveSeconds="259200" 15 memoryStoreEvictionPolicy="LRU"/> 16 17 <cache 18 name="cloud_user" 19 eternal="false" 20 maxElementsInMemory="5000" 21 overflowToDisk="false" 22 diskPersistent="false" 23 timeToIdleSeconds="1800" 24 timeToLiveSeconds="1800" 25 memoryStoreEvictionPolicy="LRU"/> 26 </ehcache>

浙公网安备 33010602011771号