dqyitt2954 2017-02-27 17:25
浏览 174
已采纳

gopkg.in/mgo.v2中的并发(Mongo,Go)

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.

  • 写回答

2条回答 默认 最新

  • ds2010630 2017-02-27 20:50
    关注

    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 Sessions: mgo - query performance seems consistently slow (500-650ms)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?