来自 mongodb 的 go 快速入门博客文章的以下代码片段(为简洁而减少)在连接数据库时创建 context.withtimeout
,并将其重用于延迟的 disconnect
函数,我认为这是有问题的。
func main() { client, _ := mongo.newclient(options.client().applyuri("<atlas_uri_here>")) ctx, _ := context.withtimeout(context.background(), 10*time.second) _ = client.connect(ctx) defer client.disconnect(ctx) }
我的思路-
context.withtimeout
在创建时以 unix 时间设置截止时间。
因此,将其传递给 connect
是有意义的,因为我们希望在超过时间限制(即派生的 unix 时间)时取消建立连接的过程。
现在,将相同的 ctx
传递给延迟的 disconnect
(很可能在将来稍后调用)将导致 ctx
的时间成为过去。意思是,当函数开始执行时它就已经过期了。这不是预期的结果,并且破坏了引用 disconnect
文档的逻辑-
If the context expires via cancellation, deadline, or timeout before the in use connections have returned, the in use connections will be closed, resulting in the failure of any in flight read or write operations.
请告诉我是否以及如何错误和/或遗漏了某些内容。
你的理解是正确的。
在示例中就足够了,因为示例只是连接到数据库,执行一些示例操作(例如列出数据库),然后 main()
结束,因此使用相同的上下文运行延迟断开连接不会造成任何麻烦(示例将/应该在 10 秒内运行良好)。
在“现实世界”的应用程序中,情况当然不会如此。因此,您可能不会使用相同的上下文进行连接和断开连接(除非该上下文没有超时)。