如何正确使用Go中的MongoDB会话?

Cor*_*ave 5 go mongodb

gopkg.in/mgo.v2在我的应用程序中使用MongoDB(包)作为数据库.根据MongoDB的最佳实践,我应该在应用程序启动时打开连接,并在应用程序终止时关闭它.要验证连接是否将关闭,我可以使用defer构造:

session, err := mgo.Dial(mongodbURL)
if err != nil {
    panic(err)
}
defer session.Close()
Run Code Online (Sandbox Code Playgroud)

如果我在main函数中执行此代码,那么一切都会好的.但我希望将此代码放在单独的go文件中.如果我执行此会话将在执行方法后关闭.根据MongoDB最佳实践,在Golang中打开和关闭会话的最佳方法是什么?

Mon*_*eep 7

你可以做这样的事情.创建一个执行Db初始化的包

    package common

    import "gopkg.in/mgo.v2"

    var mgoSession   *mgo.Session

    // Creates a new session if mgoSession is nil i.e there is no active mongo session. 
   //If there is an active mongo session it will return a Clone
    func GetMongoSession() *mgo.Session {
        if mgoSession == nil {
            var err error
            mgoSession, err = mgo.Dial(mongo_conn_str)
            if err != nil {
                log.Fatal("Failed to start the Mongo session")
            }
        }
        return mgoSession.Clone()
    }
Run Code Online (Sandbox Code Playgroud)

克隆重用与原始会话相同的套接字.

现在在其他包中,您可以调用此方法:

package main

session := common.GetMongoSession()
defer session.Close()
Run Code Online (Sandbox Code Playgroud)