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

我已经玩了一段时间了,我喜欢它,但它似乎有一些与其他语言不同的东西。所以我在写一个使用MongoDB的与web应用程序的MgO包。我想知道保持数据库会话打开以在其他包(我的模型)中使用的最佳做法是什么。


请随时纠正我可能有的任何错误理想,我才开始使用 GO。


以下是我的想法:


package main


import(

    ds "api-v2/datastore"

)


type Log struct {

    Name string

}


func main() {

    sesh := ds.Sesh


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

}

在我的数据存储包中:


package datastore


import(

    "gopkg.in/mgo.v2"

)


var Sesh = newSession()


func newSession() **mgo.Session {

    session, err := mgo.Dial("localhost")

    if err != nil {

        panic(err)

    } 


    return &session

}


拉丁的传说
浏览 151回答 1
1回答

慕码人8056858

根据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此方法的执行结束之前执行代码。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go