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

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

How to correctly work with MongoDB session in Go?

问题

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

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

如果我将这段代码放在一个单独的go文件中,那么会在方法执行后关闭session。根据MongoDB的最佳实践,最好的方法是什么,以在Golang中打开和关闭session?

英文:

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?

答案1

得分: 8

你可以这样做。创建一个负责数据库初始化的包。

package common

import "gopkg.in/mgo.v2"

var mgoSession *mgo.Session

// 如果mgoSession为空,即没有活动的Mongo会话,则创建一个新的会话。
// 如果有活动的Mongo会话,则返回一个克隆会话。
func GetMongoSession() *mgo.Session {
    if mgoSession == nil {
        var err error
        mgoSession, err = mgo.Dial(mongo_conn_str)
        if err != nil {
            log.Fatal("无法启动Mongo会话")
        }
    }
    return mgoSession.Clone()
}

Clone 方法会重用与原始会话相同的套接字。

现在在其他包中,你可以调用这个方法:

package main

session := common.GetMongoSession()
defer session.Close()
英文:

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

答案2

得分: 3

将该部分代码传递给代码的其他部分,在defer()之后,

func main(){
    // ... 其他内容
    session, err := mgo.Dial(mongodbURL)
      if err != nil {
        panic(err)
      }
    defer session.Close()
    doThinginOtherFile(session) 
}

看起来,如果有一个可以克隆的会话作为克隆源,你可以克隆/复制会话。

英文:

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.

huangapple
  • 本文由 发表于 2016年4月6日 00:33:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/36432123.html
匿名

发表评论

匿名网友

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

确定