Mybatis3缓存示例
前言-Mybatis3基础
Mybatis系统中默认定义了两级缓存:一级缓存和二级缓存
- 默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)
- 二级缓存需要手动开启和配置,是基于namespace(接口)级别的缓存。
- Mybatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存。
1、一级缓存(本地缓存)
- 一级缓存是默认开启的
- 使用SqlSession对象中的clearCache()可以清除缓存
测试:
@Test
public void getUserListCacheTest() {
SqlSession session = MybatisUtils.getSession();
UserMapper userMapper = session.getMapper(UserMapper.class);
List<User> userList = userMapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
System.out.println("==============================");
List<User> userList2 = userMapper.getUserList();
for (User user : userList2) {
System.out.println(user);
}
session.close();
}
打开日志:
...
[org.apache.ibatis.datasource.pooled.PooledDataSource]-PooledDataSource forcefully closed/removed all connections.
[org.apache.ibatis.datasource.pooled.PooledDataSource]-PooledDataSource forcefully closed/removed all connections.
[org.apache.ibatis.datasource.pooled.PooledDataSource]-PooledDataSource forcefully closed/removed all connections.
[org.apache.ibatis.datasource.pooled.PooledDataSource]-PooledDataSource forcefully closed/removed all connections.
[org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Opening JDBC Connection
# 此处创建了数据库连接
[org.apache.ibatis.datasource.pooled.PooledDataSource]-Created connection 212683148.
[com.zhanc.dao.UserMapper.getUserList]-==> Preparing: select * from tbl_temp
[com.zhanc.dao.UserMapper.getUserList]-==> Parameters:
[com.zhanc.dao.UserMapper.getUserList]-<== Total: 5
User{id=1, username='zhanchangda', password='123123', dept_id=1}
User{id=2, username='aaa', password='123123', dept_id=1}
User{id=4, username='阿斯', password='123123', dept_id=1}
User{id=6, username='aokjs', password='123123', dept_id=1}
User{id=7, username='zhanc', password='123123', dept_id=1}
==============================
User{id=1, username='zhanchangda', password='123123', dept_id=1}
User{id=2, username='aaa', password='123123', dept_id=1}
User{id=4, username='阿斯', password='123123', dept_id=1}
User{id=6, username='aokjs', password='123123', dept_id=1}
User{id=7, username='zhanc', password='123123', dept_id=1}
[org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@cad498c]
# 将该连接返回到连接池
[org.apache.ibatis.datasource.pooled.PooledDataSource]-Returned connection 212683148 to pool.
Process finished with exit code 0
可以看到,两次查询使用的是同一个连接,两次查询是在同一个会话(SqlSession)中进行的
2、二级缓存
- 二级缓存也叫全局缓存,是由于一级缓存的作用域太低而诞生的。
- 基于namespace(换而言之 接口)级别的缓存,一个名称空间对应一个二级缓存
- 工作机制
- 一个会话(SqlSession)查询一条数据,这个数据就会被放在当前会话的一级缓存中
- 如果当前会话关闭了,该会话对应的一级缓存就没了;我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中
- 新的会话查询信息,就可以从二级缓存中获取内容
- 不同的mapper查出的数据会放在自己对应的缓存中(map)
步骤:
1、开启缓存
在Mybatis-config.xml中:
<settings>
...
<!--默认是true开启的,但一般显式的写出来-->
<setting name="cacheEnabled" value="true"/>
...
</settings>
2、在Mapper.xml中:
默认情况下之启用本地缓存(即一级缓存),如果要启用全局的二级缓存,只需要在Mapper.xml添加:
<cache/>
这个简单的配置效果如下:
- 映射语句文件中的所有 select 语句的结果将会被缓存。
- 映射语句文件中的所有 insert、update 和 delete 语句会刷新缓存。
- 缓存会使用最近最少使用算法(LRU, Least Recently Used)算法来清除不需要的缓存。
- 缓存不会定时进行刷新(也就是说,没有刷新间隔)。
- 缓存会保存列表或对象(无论查询方法返回哪种)的 1024 个引用。
- 缓存会被视为读/写缓存,这意味着获取到的对象并不是共享的,可以安全地被调用者修改,而不干扰其他调用者或线程所做的潜在修改。
当然,也有更高级的配置:
<cache
eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
这创建了一个 FIFO 缓存,每隔 60 秒刷新,最多可以存储结果对象或列表的 512 个引用,而且返回的对象被认为是只读的,因此对它们进行修改可能会在不同线程中的调用者产生冲突。
- eviction:缓存的清除策略(默认为LRU)
可用的清除策略有:
LRU
– 最近最少使用:移除最长时间不被使用的对象。
FIFO
– 先进先出:按对象进入缓存的顺序来移除它们。
SOFT
– 软引用:基于垃圾回收器状态和软引用规则移除对象。
WEAK
– 弱引用:更积极地基于垃圾收集器状态和弱引用规则移除对象。
- flushInterval:缓存的刷新间隔(无默认值,即缓存仅仅会在调用语句时刷新)单位毫秒
- size:引用数目(默认值为1024)
- readOnly:只读(默认值是false)只读的缓存会给所有调用者返回缓存对象的相同实例,而可读写的缓存会(通过序列化)返回缓存对象的拷贝。 速度上会慢一些,但是更安全,因此默认值是 false。当值为false时,实体类需要实现Serializable接口。
3、测试
@Test
public void getUserListTest() {
SqlSession session1 = MybatisUtils.getSession();
SqlSession session2 = MybatisUtils.getSession();
UserMapper userMapper = session1.getMapper(UserMapper.class);
List<User> userList = userMapper.getUserList();
//只有当会话提交或关闭时,才会提交到二级缓存中
session1.close();
for (User user : userList) {
System.out.println(user);
}
System.out.println("==================================");
UserMapper userMapper2 = session2.getMapper(UserMapper.class);
List<User> userList2 = userMapper2.getUserList();
session2.close();
for (User user : userList2) {
System.out.println(user);
}
}
日志:
[org.apache.ibatis.logging.LogFactory]-Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
[org.apache.ibatis.datasource.pooled.PooledDataSource]-PooledDataSource forcefully closed/removed all connections.
[org.apache.ibatis.datasource.pooled.PooledDataSource]-PooledDataSource forcefully closed/removed all connections.
[org.apache.ibatis.datasource.pooled.PooledDataSource]-PooledDataSource forcefully closed/removed all connections.
[org.apache.ibatis.datasource.pooled.PooledDataSource]-PooledDataSource forcefully closed/removed all connections.
[com.zhanc.dao.UserMapper]-Cache Hit Ratio [com.zhanc.dao.UserMapper]: 0.0
[org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Opening JDBC Connection
[org.apache.ibatis.datasource.pooled.PooledDataSource]-Created connection 586127428.
[org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@22ef9844]
[com.zhanc.dao.UserMapper.getUserList]-==> Preparing: select * from tbl_temp
[com.zhanc.dao.UserMapper.getUserList]-==> Parameters:
[com.zhanc.dao.UserMapper.getUserList]-<== Total: 5
[org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@22ef9844]
[org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@22ef9844]
[org.apache.ibatis.datasource.pooled.PooledDataSource]-Returned connection 586127428 to pool.
User{id=1, username='zhanchangda', password='123123', dept_id=1}
User{id=2, username='aaa', password='123123', dept_id=1}
User{id=4, username='阿斯', password='123123', dept_id=1}
User{id=6, username='aokjs', password='123123', dept_id=1}
User{id=7, username='zhanc', password='123123', dept_id=1}
==================================
[org.apache.ibatis.io.SerialFilterChecker]-As you are using functionality that deserializes object streams, it is recommended to define the JEP-290 serial filter. Please refer to https://docs.oracle.com/pls/topic/lookup?ctx=javase15&id=GUID-8296D8E8-2B93-4B9A-856E-0A65AF9B8C66
# 并没有新建连接 而是从缓存中获取
[com.zhanc.dao.UserMapper]-Cache Hit Ratio [com.zhanc.dao.UserMapper]: 0.5
User{id=1, username='zhanchangda', password='123123', dept_id=1}
User{id=2, username='aaa', password='123123', dept_id=1}
User{id=4, username='阿斯', password='123123', dept_id=1}
User{id=6, username='aokjs', password='123123', dept_id=1}
User{id=7, username='zhanc', password='123123', dept_id=1}
Process finished with exit code 0