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

Is there a standard way to keep a database session open across packages in Golang?

我已经使用 go 玩了一段时间,我喜欢它,但它似乎有一些与其他语言不同的地方。所以我正在编写一个使用 MongoDb 和 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
}

谢谢!

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

Every session created must have its Close method called at the end of its life time, so its resources may be put back in the pool or collected, depending on the case.

只要作业完成就需要调用Close()。并且session会在方法调用的时候返回到pool中。

此外,查看他们的源代码(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 方法对单个集群只需要一次。对后续会话使用 NewCopy,否则您将无法从连接池的优势中获益。

---更新了---

我试图创建一个示例,但我发现 @John S Perayil 的评论中的 link 的想法非常相似。

我想强调的是 Dial 方法在启动过程中只能调用 一次 ,最好将其放入 init 方法。然后您可以创建一个 returns session.Copy() 的方法(例如,newSession)。

这就是调用方法的方式:

func main() {
    session := ds.NewSession()
    defer session.Close()

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

不知何故我注意到你没有在你的代码中调用 defer session.Close()defer 将在该方法执行结束之前立即执行代码。