cursor是啥
研究cursor如何避免oom异常之前,先了解一下cursor是啥。
在mybatis中,有一个特殊的对象cursor
,这个对象的注释上清晰的说明了,这个类的用途。
/** * cursor contract to handle fetching items lazily using an iterator. * cursors are a perfect fit to handle millions of items queries that would not normally fits in memory. * if you use collections in resultmaps then cursor sql queries must be ordered (resultordered="true") * using the id columns of the resultmap. * * @author guillaume darmont / guillaume@dropinocean.com */
cursors are a perfect fit to handle millions of items queries that would not normally fits in memory. cursor非常适合处理通常不适合内存的数百万项查询
甚至在说明中还着重的说明了是非常适合的。
这个类的作用其实就是为了避免在数据库批量查询到大数据时导致程序oom错误。
如何使用cursor
在mybatis中使用cursor非常简单,只要在mapper文件中将方法的返回值设置成cursor<t>
即可。
@select("select * from log") cursor<log> selectall();
注意:要是想在springboot中使用cursor的话,需要下面方式二选一,不然的话使用cursor会报错。
- 手动创建sqlsession
- 在调用mapper方法的方法上标注
@transactional
事务注解。
之所以需要额外配置是因为在springboot中,mybatis的sqlsession生命周期只在mapper方法中,并且在关闭sqlsession时,还会将sqlsession**绑定的cursor关闭,**所以就需要延长sqlsession的存活时间了。
cursor原理
解析mapper方法返回值
在mybatis中,调用mapper方法时,会由mapperproxy
进行方法的代理。此时就会根据具体的方法进行不同的解析
public methodsignature(configuration configuration, class<?> mapperinterface, method method) { // 解析方法返回值 type resolvedreturntype = typeparameterresolver.resolvereturntype(method, mapperinterface); if (resolvedreturntype instanceof class<?>) { this.returntype = (class<?>) resolvedreturntype; } else if (resolvedreturntype instanceof parameterizedtype) { this.returntype = (class<?>) ((parameterizedtype) resolvedreturntype).getrawtype(); } else { this.returntype = method.getreturntype(); } this.returnsvoid = void.class.equals(this.returntype); this.returnsmany = configuration.getobjectfactory().iscollection(this.returntype) || this.returntype.isarray(); // 方法是否返回cursor类型 this.returnscursor = cursor.class.equals(this.returntype); this.returnsoptional = optional.class.equals(this.returntype); this.mapkey = getmapkey(method); this.returnsmap = this.mapkey != null; this.rowboundsindex = getuniqueparamindex(method, rowbounds.class); this.resulthandlerindex = getuniqueparamindex(method, resulthandler.class); this.paramnameresolver = new paramnameresolver(configuration, method); }
根据cursor返回值调用selectcursor
解析mapper方法得到返回值后,就会根据返回值的类型来决定具体调用的查询方法。
public object execute(sqlsession sqlsession, object[] args) { object result; switch (command.gettype()) { // ---------- 其他查询---------------- case select: if (method.returnsvoid() && method.hasresulthandler()) { executewithresulthandler(sqlsession, args); result = null; } else if (method.returnsmany()) { result = executeformany(sqlsession, args); } else if (method.returnsmap()) { result = executeformap(sqlsession, args); } else if (method.returnscursor()) { // cursor返回类型 result = executeforcursor(sqlsession, args); } else { object param = method.convertargstosqlcommandparam(args); result = sqlsession.selectone(command.getname(), param); if (method.returnsoptional() && (result == null || !method.getreturntype().equals(result.getclass()))) { result = optional.ofnullable(result); } } break; // ---------- 其他查询---------------- return result; }
构建statement
使用上面解析mapper方法后得到的sql,从数据库链接中创建一个preparedstatement
并填充对应的参数值。
private statement preparestatement(statementhandler handler, log statementlog) throws sqlexception { statement stmt; connection connection = getconnection(statementlog); stmt = handler.prepare(connection, transaction.gettimeout()); handler.parameterize(stmt); return stmt; }
封装cursor
在调用的最后,会将从数据库得到的resultset
以及mybatis内部的resultsethandler
封装成cursor
对象供用户使用。
public <e> cursor<e> handlecursorresultsets(statement stmt) throws sqlexception { errorcontext.instance().activity("handling cursor results").object(mappedstatement.getid()); resultsetwrapper rsw = getfirstresultset(stmt); list<resultmap> resultmaps = mappedstatement.getresultmaps(); int resultmapcount = resultmaps.size(); validateresultmapscount(rsw, resultmapcount); if (resultmapcount != 1) { throw new executorexception("cursor results cannot be mapped to multiple resultmaps"); } resultmap resultmap = resultmaps.get(0); return new defaultcursor<>(this, resultmap, rsw, rowbounds); }
为啥能避免内存溢出
在讨论这个问题前,我们可以看一下在mybatis中,cursor返回值的查询以及批量查询的实际调用逻辑。
cursor查询
@override protected <e> cursor<e> doquerycursor(mappedstatement ms, object parameter, rowbounds rowbounds, boundsql boundsql) throws sqlexception { configuration configuration = ms.getconfiguration(); statementhandler handler = configuration.newstatementhandler(wrapper, ms, parameter, rowbounds, null, boundsql); statement stmt = preparestatement(handler, ms.getstatementlog()); cursor<e> cursor = handler.querycursor(stmt); stmt.closeoncompletion(); return cursor; }
批量查询
@override public <e> list<e> doquery(mappedstatement ms, object parameter, rowbounds rowbounds, resulthandler resulthandler, boundsql boundsql) throws sqlexception { statement stmt = null; try { configuration configuration = ms.getconfiguration(); statementhandler handler = configuration.newstatementhandler(wrapper, ms, parameter, rowbounds, resulthandler, boundsql); stmt = preparestatement(handler, ms.getstatementlog()); return handler.query(stmt, resulthandler); } finally { closestatement(stmt); } }
可以对比一下两个实际执行的方法,比较明显的区别就是在批量搜索中,显式关闭了打开的statement
,而在cursor查询中,并没有关闭与数据库的连接。归根结底就是因为cursor在使用上就是在操作原生的statement
,故不能在查询后关闭。
另外,在批量查询的handler.query(stmt, resulthandler)
方法中,是获取本次查询的所有数据后返回的,而这就会导致在大批量数据时塞爆内存导致oom了。
然而在cursor查询中,并不会获取全部数据后返回,而是根据用户操作来获取对于数据,自然而然也就不会塞爆内存了。
总结
类型 | 如何获取数据 | 返回值 | 是否关闭statement、resultset |
---|---|---|---|
cursor | 用户自行根据cursor迭代器获取 | cursor游标类型 | 不关闭,需要一直持有 |
普通搜索 | mybatis内部操控jdbc指针,获取所有查询数据后返回。 | 具体实体类型 | 获取完数据后关闭 |
以上就是mybatis的cursor避免oom异常的方法详解的详细内容,更多关于mybatis cursor避免oom异常的资料请关注代码网其它相关文章!
发表评论