go与数据库交互
原创
©著作权归作者所有:来自51CTO博客作者demo123567的原创作品,请联系作者获取转载授权,否则将追究法律责任
go(四)
来谈谈go语言与mongodb的交互
首先,定义几个连接变量
var (
mgoSession *mgo.Session
logSession *mgo.Session
sequenceC = "sequence"
)
然后定义一些配置变量:
var dbUrl string
var gameDb string
var userDb string
var logDb string
var logDbUrl string
var dbPoolLimit int
给配置变量绑定数据
flag.StringVar(&dbUrl, "db", "127.0.0.1", "db url.")
flag.StringVar(&logDbUrl, "logDBUrl", "", "logdb url.")
flag.StringVar(&gameDb, "gameDB", "poker_game", "gameDB名称")
flag.StringVar(&userDb, "userDB", "poker_user", "userDB名称")
flag.StringVar(&logDb, "logDB", "poker_log", "logDB名称")
flag.IntVar(&dbPoolLimit, "dbPoolLimit", 200, "数据库连接数限制")
然后,得到连接
func getSession() *mgo.Session {
if mgoSession == nil {
var err error
mgoSession, err = mgo.Dial(dbUrl)
if err != nil {
panic(err)
}
mgoSession.SetPoolLimit(dbPoolLimit)
}
return mgoSession.Clone()
}
然后写个操作数据库的方法就可以了
func WithGameCollection(collection string, s func(*mgo.Collection) error) error {
session := getSession()
defer session.Close()
c := session.DB(gameDb).C(collection)
return s(c)
}