1 回答

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此方法的执行结束之前执行代码。
- 1 回答
- 0 关注
- 150 浏览
添加回答
举报