douqiang3768
douqiang3768
2016-04-05 16:33

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

已采纳

I'm using MongoDB (gopkg.in/mgo.v2 package) as a database in my go app. According to MongoDB best practices I should to open connection when application starting and close it when application is terminating. To verify that connection will be closed I can use defer construction:

session, err := mgo.Dial(mongodbURL)
if err != nil {
    panic(err)
}
defer session.Close()

All will be good if I execute this code in main function. But I want to have this code in separate go file. If I do this session will be closed after method will be executed.What is the best way to open and close session in Golang according MongoDB best practices?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • dongyao2129 dongyao2129 5年前

    You can do something like this. Create a package which does the Db initialization

        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()
        }
    

    Clone reuses the same socket as the original session.

    Now in other packages you can call this method:

    package main
    
    session := common.GetMongoSession()
    defer session.Close()
    
    点赞 评论 复制链接分享
  • duanpao4522 duanpao4522 5年前

    Pass the section to the other part of the code after the defer(),

    func main(){
        // ... other stuff
        session, err := mgo.Dial(mongodbURL)
          if err != nil {
            panic(err)
          }
        defer session.Close()
        doThinginOtherFile(session) 
    }
    

    It looks like you can clone/copy sessions if necessary as long as you have one to clone from.

    点赞 评论 复制链接分享