英文:
When mongodb client should disconnect after instantiating client?
问题
根据文档中的说明:
> 在实例化客户端后,请确保延迟调用 Disconnect
:
defer func() {
if err = client.Disconnect(ctx); err != nil {
panic(err)
}
}()
上述文档是否意味着在程序关闭期间(使用mongodb驱动程序)断开连接?
英文:
As per the documentation in Readme:
> Make sure to defer a call to Disconnect
after instantiating your client:
defer func() {
if err = client.Disconnect(ctx); err != nil {
panic(err)
}
}()
Does the above documentation meant to disconnect, during shutdown of the program(using mongodb driver)?
答案1
得分: 3
他们只是提醒你应该在某个时刻关闭与数据库的连接。具体什么时候关闭取决于你。通常情况下,你会在应用程序的顶层初始化数据库连接,所以defer调用应该在同一级别。例如,
func main() {
client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
defer func() {
if err = client.Disconnect(ctx); err != nil {
panic(err)
}
}()
// 将连接传递给应用程序的其他组件
doSomeWork(client)
}
注意:如果你在使用Goroutines,请不要忘记在主函数中对它们进行同步,否则连接将会过早关闭。
英文:
They just reminded you that you should always close the connection to the database at some point. When exactly is up to you. Usually, you initialize the database connection at the top-level of your application, so the defer call should be at the same level. For example,
func main() {
client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
defer func() {
if err = client.Disconnect(ctx); err != nil {
panic(err)
}
}()
// Pass the connection to other components of your appliaction
doSomeWork(client)
}
Note: If you are using Goroutines don't forget to synchronize them in main otherwise the connection will be close too early.
答案2
得分: 2
我认为文档意思是在程序的main函数中使用defer
和client.Disconnect
。通过这样做,你的程序将在退出之前关闭所有的MongoDB客户端连接。
如果你在一个准备客户端的辅助函数中使用它,它将在客户端创建后立即关闭所有连接,这可能不是你想要的。
英文:
I think the documentation meant to use defer
with client.Disconnect
in the main function of your program. Thanks to that your program will close all the MongoDB client connections before exiting.
If you would use it e.g. in a helper function that prepares that client, it would close all the connections right after the client creation which may not be something you want.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论