gopkg.in/mgo.v2中的并发(Mongo,Go) [英] Concurrency in gopkg.in/mgo.v2 (Mongo, Go)
问题描述
我可以有一个 mgo.Session
和在Web应用程序中同时使用它。例如在 http.Handler
或者我应该调用 Session.Copy
和 Session.Close
- >创建会话池。
这听起来很矛盾,已经在 mgo.Session
内部实现了,我可以同时使用会话,并且在其他地方读到我需要 Copy
和关闭
。
mgo.Session
对于并发使用是安全的。引用它的文档:
所有会话方法都是并发安全的,可以从多个goroutine调用。
但这并不意味着你不应该通过调用 Session.Copy()
或 Session.Clone()
,获得初始会话在拨号时间。
并发安全并且从使用更多应用程序中受益不会互相排斥(它们不是互斥的 ) 。虽然你可以从任意数量的例程中使用一个 mgo.Session
,但这不会很好地扩展,它根本不会扩展 。会话自动管理连接池,甚至可以连接到多个服务器节点,但如果您使用的是单个 Session
,那么您没有充分利用这一点。通过在每个请求开始时(如果需要)创建一个新的 Session
,并在最后正确关闭它(使用 Session.Close()
;最好使用 defer
),那么您正在利用可能同时使用多个连接的可能性,可能会使用多个服务器节点(如果可用),从而更好地利用服务器资源;并获得更快的响应时间(无论是从数据库,最终到您的HTTP最终用户)。调用 Session.Close()
不会关闭到服务器的底层连接,它只会将连接放回池中,准备被另一个会话接收。 / p>
I wish to use MongoDB in webapp written in Go.
Can I have one mgo.Session
and use it concurrently in web app. e.g. in http.Handler
or should I call Session.Copy
and Session.Close
-> make pool of sessions.
It sounds contradictory somewhere I read that pool is already implemented inside of mgo.Session
and I can use session concurrently and in other places I read that I need Copy
and Close
.
The mgo.Session
is safe for concurrent use. Quoting from its doc:
All Session methods are concurrency-safe and may be called from multiple goroutines.
But this doesn't mean you should not create and use more of them in parallel, by calling Session.Copy()
or Session.Clone()
, on the initial session obtained at dial time.
Being concurrency-safe and having benefit from using more of them do not exclude each other (they are not mutually exclusive). While you may use a single mgo.Session
from arbitrary number of goroutines, that will not scale well, that will not scale at all. Sessions automatically manage a pool of connections, maybe even to multiple server nodes, but if you're using a single Session
, you're not taking advantage of that. By creating a new Session
at the start of each of your request (if needed), and properly closing it at the end (with Session.Close()
; preferably called using defer
), you are taking advantage of potentially using multiple connections at the same time, possibly to multiple server nodes (if available), and thus better utilizing server resources; and getting faster response times (both from the database, and ultimately to your HTTP end users). Calling Session.Close()
does not close the underlying connection to the server, it will just put the connection back to the pool, ready to be picked up by another session.
Also see related question about the use of Session
s: mgo - query performance seems consistently slow (500-650ms)
这篇关于gopkg.in/mgo.v2中的并发(Mongo,Go)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!