douqiang3768
2016-04-05 16:33
浏览 107

如何在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?

图片转代码服务由CSDN问答提供 功能建议

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

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

如果我在 main < / code>函数。 但是我想将此代码放在单独的go文件中。 如果我这样做,将在执行方法后关闭会话。根据MongoDB最佳实践,在Golang中打开和关闭会话的最佳方法是什么?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongyao2129 2016-04-05 16:46
    已采纳

    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 2016-04-05 16:49

    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.

    点赞 打赏 评论

相关推荐 更多相似问题