
在数据库查询 *** 作中,多次查询相同数据的情况是可以通过将数据先保存起来,后续查询直接从内存取的方式进行优化,缓存就是这样。
缓存通常用于查询次数较多且变化较少的数据。
默认定义两级缓存:
一级缓存sqlSession级别,本地缓存
二级缓存namespace(mapper接口)级别:需要手动开启,可以通过cache接口自定义二级缓存
sqlSession级别缓存,即在一次sqlSession中,查询相同内容,只会执行一次sql查询,将结果放到内存,后续所有查询结果都将指向第一次查询结果。
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user1 = mapper.getUsersById(1);
System.out.println(user1);
User user2 = mapper.getUsersById(1);
System.out.println(user2);
System.out.println(user1.equals(user2));
缓存失效:
①查询不同
②两次相同查询间,对数据库任意内容进行了修改,即增删改 *** 作
③查询不同mapper.xml
④手动清空缓存
默认只启动一级缓存,启动二级缓存方式:
①开启全局缓存
<setting name="cacheEnabled" value="true"/>
显式开启全局缓存
②在mapper插入cache标签
<cache/>
可以用内部标签细分类:
<cache eviction="LRU"
flushInterval="60000"
size="512"
readOnly="true"/>
可用清除策略:
①LRU最近最少使用
②FIFO先进先出
③SOFT软引用
④WEAK弱引用
一个会话查询一条数据,该数据会保存到一级缓存;
当会话关闭,一级缓存内容将会被保存到二级缓存内,这样新的会话就可以从二级缓存中获取数据。
不同mapper保存到自己不同的缓存中
SqlSession sqlSession = MybatisUtils.getSqlSession();
SqlSession sqlSession2 = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user1 = mapper.getUsersById(1);
System.out.println(user1);
sqlSession.close();
UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class);
User user2 = mapper2.getUsersById(1);
System.out.println(user2);
System.out.println(user1.equals(user2));
代码只进行一次查询,且user1==user2
注意事项①注解形式的sql经过上述 *** 作仍然查询两次,只有在mapper中写的才会执行二级缓存
②实体类需要序列化public class User implements Serializable
③缓存中ReadOnly属性,将决定二级缓存的多次内容是否相同,当为false,由于可读写,将会返回用户一个内容副本,防止其直接对二级缓存内容更改,更加安全,而true会使其都指向一个结果。
第一次查询:多个SqlSession对一个数据库进行查询,每个SqlSession将结果先缓存到各自内的一级缓存空间。
当SqlSession关闭:将其内部一级缓存保存的数据放到Mapper的二级缓存空间内。
用户查询:先在二级缓存中查询,再在一级缓存查询,都没有再查询数据库
导入:
<dependency>
<groupId>org.mybatis.cachesgroupId>
<artifactId>mybatis-ehcacheartifactId>
<version>1.1.0version>
dependency>
mapper:
<cache type="com.org.mybatis.caches.ehcache.EhcacheCache"/>
ehcache.xml配置文件:
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd" updateCheck="false">
<diskStore path="./tempdir/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>
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)