什么是缓存[Cache]?
存在内存中的临时数据将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题。为什么使用缓存?
减少和数据库的交互次数,减少系统开销,提高系统效率什么样的数据能使用缓存?
经常查询并且不经常改变的数据。测试步骤:
开启日志!配置文件中配置
<settings> <!--标准的日志工厂实现--> <setting name="logImpl" value="STDOUT_LOGGING"/> <!--名字必须和官网一样,不能有有空格--> </settings>2.测试在一个Sesion中查询两次相同的记录
3.查看日志输出
@Test public void getUserById(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user1 = mapper.getUserById(1); System.out.println(user1); System.out.println("==================================="); User user2 = mapper.getUserById(1); System.out.println(user2); System.out.println(user1==user2); sqlSession.close(); }缓存失败的情况:
查询不同的东西
增删改操作,可能会改变原来的数据,所以必定会刷新缓存!
查询不同的Mapper.xml
手动清理缓存
sqlSession.clearCache();//手动清理缓存小结:一级缓存默认是开启的,只在一次sqlSession中有效,也就是建立连接到关闭连接这个区间段!
一级缓存相当于Map集合
步骤:
开启全局缓存,在核心配置文件中设置
<settings> <!--显示的开启全局缓存--> <setting name="cacheEnabled" value="true"/> </settings>2.在要使用二级缓存的Mapper中开启
<!--在当前Mapper.xml中使用二级缓存--> <cache/>也可以自定义参数
<!--在当前Mapper.xml中使用二级缓存--> <cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true" />3.测试
@Test public void getUserById(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user1 = mapper.getUserById(1); System.out.println(user1); sqlSession.close(); System.out.println("==================================="); SqlSession sqlSession1 = MybatisUtils.getSqlSession(); UserMapper mapper1 = sqlSession1.getMapper(UserMapper.class); User user2 = mapper1.getUserById(1); System.out.println(user2); System.out.println(user1==user2); sqlSession1.close(); }1.问题:我们需要将实体类序列化!否则就会报错!
Cause: java.io.NotSerializableException: com.cfeng.pojo.User小结:
只要开启了二级缓存,在同一个Mapper下就有效所有的数据都会先放在一级缓存中;只有当会话提交,或者关闭的时候(sqlSession.close();),才会提交到二级缓存中要在程序中使用ehcahe,要先在pom.xml中导包
<!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache --> <dependency> <groupId>org.mybatis.caches</groupId> <artifactId>mybatis-ehcache</artifactId> <version>1.1.0</version> </dependency>在resources中创建eacache.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>在Mapper.xml中使用
<!--在当前Mapper.xml中使用二级缓存--> <cache type="org.mybatis.caches.ehcache.EhcacheCache"/>目前我们使用Redis数据库来做缓存!(使用K-V)
