<p>Hello guys. I have a system with about 100 req/sec. And sometimes it doesn't respond until I restart my go program. I found out that this is because I open transaction and don't close it in some places. That's why all connections were occupied by opened transactions and I couldn't open another one
After this I added this code</p>
<pre><code>defer func() {
if r := recover(); r != nil {
tx.Rollback()
return
}
if err == nil {
err = tx.Commit()
} else {
tx.Rollback()
}
}()
</code></pre>
<p>This made my program work for a month without interruption. But just now it happened again. Probably because of this issue. Is there a better way to close transaction? Or maybe a way to close a transaction if it was open for 1 minute?</p>
<hr/>**评论:**<br/><br/>tgulacsi: <pre><p>If this is database/sql, go1.8 has some Context additions.
But I bet you have another place where you miss closing a file handle. To check, use lsof!
And check closing of request/response Bodys.</p></pre>PsyWolf: <pre><p>Closing over err in a defer'd func like that is pretty unreliable. Most go programs reuse the err variable for different things, so it might not even refer to a db error when this gets executed. Furthermore, it's not uncommon to shadow err inside an if statement. If a shadowed err is getting set, then you're not actually setting the outer err that this code will check. The solution would be either to handle your errors closer to where they are caused, or use <a href="https://blog.golang.org/errors-are-values" rel="nofollow">a pattern like this</a> to explicitly store an error to be handled later.</p>
<p>A bug like this would present itself as either a commit that should have been a rollback or visa versa. It wouldn't leak transactions, so it's probably not causing the problem that you're asking about. That said, you should consider cleaning it up.</p></pre>Drakie: <pre><p>you can actually defer tx.Rollback() after opening and if you tx.Commit() before returning the rollback will have no effect (it will error but silently) </p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传