Golang transaction exit handling

agolangf · · 402 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Hello guys. I have a system with about 100 req/sec. And sometimes it doesn&#39;t respond until I restart my go program. I found out that this is because I open transaction and don&#39;t close it in some places. That&#39;s why all connections were occupied by opened transactions and I couldn&#39;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&#39;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&#39;s not uncommon to shadow err inside an if statement. If a shadowed err is getting set, then you&#39;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&#39;t leak transactions, so it&#39;s probably not causing the problem that you&#39;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

402 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传