[英]How to maintain MongoDB session throughout out application in goLang as global variable
I am a beginner in GoLang.我是 GoLang 的初学者。 I want to maintain a MongoDB session throughout the application.
我想在整个应用程序中维护一个 MongoDB 会话。 I already have seen answers like binding DB session in martini framework or assigning it to a goLang structs.
我已经看到了诸如在 martini 框架中绑定 DB 会话或将其分配给 goLang 结构之类的答案。 But I want a straight forward method.
但我想要一个直接的方法。
I'm assuming you've already got the mgo
driver:我假设你已经有了
mgo
驱动程序:
go get gopkg.in/mgo.v2
In your code you can set a global variable outside your main
function like:在您的代码中,您可以在
main
函数之外设置一个全局变量,例如:
var mgoSession *mgo.Session
Then either in an init
function or right in your main
function you start up your session:然后在
init
函数中或在main
函数中启动会话:
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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.