gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 01:39:10 26 4
gpt4 key购买 nike

我现在使用 go 已经有一段时间了,我喜欢它,但它似乎有一些与其他语言不同的地方。所以我正在编写一个使用 MongoDb 和 mgo 的网络应用程序包裹。我想知道保持数据库 session 打开以用于其他包(我的模型)的最佳做法是什么。

如果我有任何错误的想法,请随时纠正我,我才开始使用 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将返回到池中。

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

--- 已更新---

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

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

这就是调用方法的方式:

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

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

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

关于mongodb - 是否有一种标准方法可以在 Golang 中跨包保持数据库 session 打开?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37041430/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com