在实例化客户端后,MongoDB客户端应该在什么时候断开连接?

huangapple go评论81阅读模式
英文:

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函数中使用deferclient.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.

huangapple
  • 本文由 发表于 2022年8月15日 01:57:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/73353935.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定