ecodeclub / eorm

简单 ORM 框架
Apache License 2.0
191 stars 64 forks source link

修复单条查询时连接泄露问题 #188

Closed hookokoko closed 1 year ago

hookokoko commented 1 year ago

在ecron中是用eorm获取单条数据时,在task续约的时候会产生大量单结果查询,当超过150个select之后出现:

&mysql.MySQLError{Number:0x410, Message:"Too many connections"}

这种就是连接泄露了。看了下源码,只要在执行完for rows.Next() 遍历之后,这个连接就会被关闭,这里是Next源码:

func (rs *Rows) Next() bool {
    var doClose, ok bool
    withLock(rs.closemu.RLocker(), func() {
        // 这里如果读到最后一个数据,doClose为true,
        // 此时才会关闭,如果for Next()时数据没有遍历完就中断了,
        // 则就不会执行,那么这个连接就泄露了。
        doClose, ok = rs.nextLocked()
    })
    if doClose {
        rs.Close()
    }
    return ok
}

所以,改进就是在执行完 rows, err := sess.queryContext(ctx, qc.q.SQL, qc.q.Args...) 之后调用下rows.Close()

codecov[bot] commented 1 year ago

Codecov Report

Merging #188 (bc3a0ef) into dev (a97835a) will increase coverage by 0.01%. The diff coverage is 100.00%.

:exclamation: Current head bc3a0ef differs from pull request most recent head 446b1bf. Consider uploading reports for the commit 446b1bf to get more accurate results

@@            Coverage Diff             @@
##              dev     #188      +/-   ##
==========================================
+ Coverage   81.82%   81.83%   +0.01%     
==========================================
  Files          33       33              
  Lines        2657     2659       +2     
==========================================
+ Hits         2174     2176       +2     
  Misses        404      404              
  Partials       79       79              
Impacted Files Coverage Δ
core.go 95.31% <100.00%> (+0.15%) :arrow_up:

:mega: We’re building smart automated test selection to slash your CI/CD build times. Learn more