我在go go app中使用MongoDB(defer
包)作为数据库。根据MongoDB的最佳实践,我应该在应用程序启动时打开连接,并在应用程序终止时关闭它。要验证连接是否已关闭,我可以使用session, err := mgo.Dial(mongodbURL)
if err != nil {
panic(err)
}
defer session.Close()
构造:
main
如果我在structure(list(City = c("MUMBAI", "DELHI", "KOLKATTA", "HYDERABAD",
"PUNE", "BANGALORE", "AHMEDABAD", "LUCKNOW", "AGRA", "BHUBANESHWAR",
"GUWAHATI", "NAGPUR", "DELHIN.C.R", "MANGALORE", "INDORE"), OppLoss = c(48,
44, 41, 38, 56, 43, 44, 43, 42, 32, 31, 43, 47, 25, 41)), .Names = c("City",
"OppLoss"), row.names = c(32L, 13L, 26L, 17L, 35L, 5L, 2L, 27L,
1L, 8L, 16L, 33L, 14L, 30L, 18L), class = "data.frame")
函数中执行此代码,那么一切都会好的。但我希望将此代码放在单独的go文件中。如果我执行此会话将在执行方法后关闭。根据MongoDB最佳实践,在Golang中打开和关闭会话的最佳方法是什么?
答案 0 :(得分:6)
你可以这样做。创建一个执行Db初始化的包
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重用与原始会话相同的套接字。
现在在其他包中你可以调用这个方法:
package main
session := common.GetMongoSession()
defer session.Close()
答案 1 :(得分:3)
将该部分传递给代码的其他部分 在defer()之后,
func main(){
// ... other stuff
session, err := mgo.Dial(mongodbURL)
if err != nil {
panic(err)
}
defer session.Close()
doThinginOtherFile(session)
}
看起来你可以在必要时克隆/复制会话,只要你有一个要克隆的会话。