为了账号安全,请及时绑定邮箱和手机立即绑定

有没有一种标准方法可以在 Golang 中跨包保持数据库会话打开?

有没有一种标准方法可以在 Golang 中跨包保持数据库会话打开?

Go
拉丁的传说 2022-01-10 10:52:01
我已经玩了一段时间了,我喜欢它,但它似乎有一些与其他语言不同的东西。所以我在写一个使用MongoDB的与web应用程序的MgO包。我想知道保持数据库会话打开以在其他包(我的模型)中使用的最佳做法是什么。请随时纠正我可能有的任何错误理想,我才开始使用 GO。以下是我的想法:package mainimport(    ds "api-v2/datastore")type Log struct {    Name string}func main() {    sesh := ds.Sesh    err = &sesh.Insert(&Log{"Ale"})}在我的数据存储包中:package datastoreimport(    "gopkg.in/mgo.v2")var Sesh = newSession()func newSession() **mgo.Session {    session, err := mgo.Dial("localhost")    if err != nil {        panic(err)    }     return &session}
查看完整描述

1 回答

?
慕码人8056858

TA贡献1803条经验 获得超6个赞

根据mgo的文档,https : //godoc.org/gopkg.in/mgo.v2:


创建的每个会话都必须在其生命周期结束时调用其 Close 方法,因此其资源可能会被放回池中或收集,具体取决于具体情况。


在Close()作为作业完成需要被称为长。调用该方法时,会话将返回到池中。


另外,查看他们的源代码(https://github.com/go-mgo/mgo/blob/v2-unstable/session.go#L161),对该Dial方法有一些评论


// This method is generally called just once for a given cluster.  Further

// sessions to the same cluster are then established using the New or Copy

// methods on the obtained session. This will make them share the underlying

// cluster, and manage the pool of connections appropriately.

//

// Once the session is not useful anymore, Close must be called to release the

// resources appropriately.

Dial对于单个集群,该方法只需要一次。使用NeworCopy用于后续会话,否则您将无法从连接池的优势中受益。


- - 更新 - -


我试图创建一个示例,但我发现来自@John S Perayil评论的链接具有非常相似的想法。


我想强调的是,在启动过程中Dial你应该只调用一次的init方法,把它放在一个方法中是个好主意。然后您可以创建一个newSession返回session.Copy().


所以这就是你调用该方法的方式:


func main() {

    session := ds.NewSession()

    defer session.Close()


    err = &session.Insert(&Log{"Ale"})

}

不知何故,我注意到您没有defer session.Close()在代码中调用,而是在defer此方法的执行结束之前执行代码。


查看完整回答
反对 回复 2022-01-10
  • 1 回答
  • 0 关注
  • 150 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号