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 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能