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

时间:2016-05-05 02:42:43

标签: mongodb go mgo database

我现在一直在玩,我喜欢它,但它似乎有一些与其他语言不同的东西。所以我正在编写一个使用MongoDb和mgo包的网络应用程序。我想知道保持数据库会话在其他包(我的模型)中打开的最佳实践是什么。

如果我有任何错误的理想,请随意纠正我,我只是开始使用GO。

继承人的想法:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>Products</h3>

<label>
  <input type="radio" name="product" value="p1" checked> Product 1
</label>
<label>
  <input type="radio" name="product" value="p2"> Product 2
</label>

<h3>Styles</h3>

<label>
  <input type="radio" name="style" value="s1" checked> Style 1
</label>
<label>
  <input type="radio" name="style" value="s2"> Style 2
</label>
<label>
  <input type="radio" name="style" value="s3"> Style 3
</label>

<h3>Quantity</h3>

<input type="number" name="quantity" value="150">

<h3>Wrap individually</h3>
<label>
  <input type="radio" name="wrap" value="no" checked> No
</label>
<label>
  <input type="radio" name="wrap" value="yes"> Yes (+ $0.05 per item)
</label>

<h3>Price</h3>
$<input name="total" value="" readonly>

在我的数据存储包中:

package main

import(
    ds "api-v2/datastore"
)

type Log struct {
    Name string
}

func main() {
    sesh := ds.Sesh

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

谢谢!

1 个答案:

答案 0 :(得分:2)

根据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方法只需要一次。使用NewCopy进行后续会话,否则您将无法获得连接池的优势。

---更新---

我试图创建一个例子,但我发现来自 @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将在此方法执行结束之前执行代码。