如何在Go语言中将MongoDB会话作为全局变量在整个应用程序中进行维护

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

How to maintain MongoDB session throughout out application in goLang as global variable

问题

我是一个GoLang的初学者。我想在整个应用程序中保持一个MongoDB会话。我已经看到了一些答案,比如在martini框架中绑定DB会话或将其分配给GoLang结构体。但我想要一个简单直接的方法。

英文:

I am a beginner in GoLang. I want to maintain a MongoDB session throughout the application. I already have seen answers like binding DB session in martini framework or assigning it to a goLang structs. But I want a straight forward method.

答案1

得分: 2

我假设你已经安装了mgo驱动程序:

go get gopkg.in/mgo.v2

在你的代码中,你可以在main函数之外设置一个全局变量,如下所示:

var mgoSession *mgo.Session

然后,在init函数或者main函数中启动你的会话:

session, err := mgo.Dial("mongodb://localhost")
if err != nil {
    panic(err)
}
session.SetMode(mgo.Monotonic, true)
mgoSession = session

然后,你可以根据需要在程序的不同函数中克隆会话:

session := mgoSession.Clone()
defer session.Close()
c := session.DB("databasename").C("collectionname")
英文:

I'm assuming you've already got the mgo driver:

go get gopkg.in/mgo.v2

In your code you can set a global variable outside your main function like:

var mgoSession *mgo.Session

Then either in an init function or right in your main function you start up your session:

session, err := mgo.Dial("mongodb://localhost")
if err != nil {
	panic(err)
}
session.SetMode(mgo.Monotonic, true)
mgoSession = session

Then you can clone the session as needed in the different functions in your program:

session := mgoSession.Clone()
defer session.Close()
c := session.DB("databasename").C("collectionname")

huangapple
  • 本文由 发表于 2016年10月31日 07:07:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/40334628.html
匿名

发表评论

匿名网友

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

确定