- 存在内存中的临时数据
- 将经常查询的数据放在缓存(内存)中,在查询数据时就不用从磁盘(关系型数据库)查询,从缓存中查询能够提高查询效率,解决高并发系统的性能问题
优势:减少和数据库交互次数,减少系统开销,提高系统效率
对经常查询且不经常改变的数据使用缓存
1. MyBatis缓存
- MyBatis包含一个十分强大的查询缓存特性,能够方便地定制和配置缓存,可以极大地提升查询效率
- MyBatis系统默认定义了两级缓存:一级缓存和二级缓存
- 默认情况下,只有一级缓存开启(SqlSession级别的缓存,本地缓存)
- 二级缓存需手动开启配置,基于 namespace 级别的缓存
- 为提高扩展性,MyBatis定义了缓存接口 Cache ,通过实现 Cache 接口定义二级缓存
2. 一级缓存
本地缓存
- 与数据库同一次会话期间查询到的数据会放在本地缓存中
- 再需要相同的数据时,直接读取缓存即可,避免再次查询数据库
-
接口
public interface UserMapper { User getUserById(@Param("id") int id); int updateUser(User user); }
-
xml
<mapper namespace="com.yl.dao.UserMapper"> <select id="getUserById" parameterType="_int" resultType="user"> select * from user where id = #{id} </select> <update id="updateUser" parameterType="user"> update user set name=#{name},pwd=#{pwd} where id = #{id} </update> </mapper>
-
测试
@Test public void getUserById(){ SqlSession sqlSession = MyBatisUntils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.getUserById(1); System.out.println(user); //增删改会刷新缓存 //mapper.updateUser(new User(6, "黑黑", "qqqqqq")); //手动清理缓存 sqlSession.clearCache(); User userById = mapper.getUserById(1); System.out.println(userById); System.out.println(user==userById); sqlSession.close(); }
缓存失效
- 查询不同的数据
- 增删改会刷新缓存
- 手动清理缓存
一级缓存默认开启,只在一次SqlSession中有效(连接至关闭)
3. 二级缓存
- 全局缓存,作用域高于一级缓存
- 基于 namespace 级别的缓存,一个 namespace 对应一个二级缓存
- 机制:
- 一个会话只查询一条数据,该数据会放在当前会话的一级缓存中
- 若当前会话关闭,则其一级缓存失效;当该会话关闭时,一级缓存中的数据会被保存到二级缓存中
- 新的会话查询信息,可以从二级缓存中获取
- 不同的 mapper 查到的数据会放在自己对应的缓存(map)中
步骤:
-
开启全局缓存
<!--全局缓存 默认开启 显式定义--> <setting name="cacheEnabled" value="true"/>
-
xml 中开启
<!--全局缓存--> <cache eviction="FIFO" flushInterval="60" size="512" readOnly="true"/>
-
测试
@Test public void getUserById(){ SqlSession sqlSession = MyBatisUntils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.getUserById(1); System.out.println(user); sqlSession.close(); //增删改会刷新缓存 //mapper.updateUser(new User(6, "黑黑", "qqqqqq")); //手动清理缓存 //sqlSession.clearCache(); SqlSession sqlSession2 = MyBatisUntils.getSqlSession(); UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class); User userById = mapper2.getUserById(1); System.out.println(userById); System.out.println(user==userById); sqlSession.close(); }
-
实体类需序列化,否则报错
Caused by: java. io. NotSerializableException: com. yl. pojo.user
注意:
- 二级缓存只在同一个 Mapper 下有效
- 所有数据都会先放在一级缓存中
- 仅当会话提交或关闭时,才会提交到二级缓存中
查询顺序:二级缓存 --> 一级缓存 --> 数据库
4. 自定义缓存(ehcache)
开源 Java 分布式缓存,面向通用缓存
导包
<!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.2.2</version>
</dependency>
UserMapper.xml 中指定 ehcache 缓存实现
<!--自定义缓存-->
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
配置文件 ehcache.xml
<?xml version="1.0" encoding="GBK"?>
<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>
<!--
diskStore:为缓存路径,ehcache分为内存和磁盘两级,此属性定义磁盘的缓存位置。参数解释如下:
user.home – 用户主目录
user.dir – 用户当前工作目录
tmpdir – 默认临时文件路径
-->
<!--
defaultCache:默认缓存策略,当ehcache找不到定义的缓存时,则使用这个缓存策略。只能定义一个。
-->
<!--
name:缓存名称。
maxElementsInMemory:缓存最大数目
maxElementsOnDisk:硬盘最大缓存个数。
eternal:对象是否永久有效,一但设置了,timeout将不起作用。
overflowToDisk:是否保存到磁盘,当系统当机时
timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
clearOnFlush:内存数量最大时是否清除。
memoryStoreEvictionPolicy:可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。
FIFO,first in first out,这个是大家最熟的,先进先出。
LFU, Less Frequently Used,就是上面例子中使用的策略,直白一点就是讲一直以来最少被使用的。如上面所讲,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。
LRU,Least Recently Used,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
-->
Redis数据库做缓存,键值对