douju2012 2019-07-10 22:00
浏览 191
已采纳

在golang中使用全局mongo(mgo)数据库有何弊端? [关闭]

Are there any downsides if we use a global variable to handle database operations instead of passing it as an argument to functions and methods or storing it as a field in structs?

What are these downsides (if there are)?

Let's say we create a package inside a project called database, inside that package define a variable called DB var DB *mgo.Database, and then in project's main function fill it with our mongo database:

func main() {
    session, err := mgo.Dial("localhost")
    if err != nil {
        fmt.Println(err)
        return
    }
    database.DB = session.DB("mydatabase")
    // project code
    defer session.Close()
}

After that, we use database.DB to interact with our database.

Note that there will be lots of goroutines using database.DB (if it makes any difference)

The question is not opinion based, please take more time to read and understand

  • 写回答

1条回答 默认 最新

  • doupeng3501 2019-07-10 23:34
    关注

    The procedure of using a globally initialized database to be handed down to the places it is needed is well established and reasonable.

    However, just using database.DB in a manner like

    _ = database.DB.C(foo).Find(q).One(&bar)
    

    all over the place holds a significant disadvantage: you only use one connection of the underlying connection pool, practically ensuring that all requests are processed sequentially.

    So what you rather want to do is something like this:

    s := database.DB.Session.Copy()
    _ = database.DB.C(foo).With(s).Find(q).One(&bar)
    defer s.Close()
    

    for „parallel“ requests (there are some caveats about parallel requests, which I leave out for the sake of brevity).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。