dqrnskni67375 2017-05-02 21:09
浏览 1687
已采纳

在Go中连接到多个数据库的最佳做法是什么?

I am trying to understand if the following is good or bad practice.

If it turns out that this is good / normal practice, it makes it easier for me to implement multiple database connectors into my project.

Situation: I have created an API server and every time a call is done to the API this piece of code runs:

ctx := context.Background()

client, err := datastore.NewClient(ctx, "foobar")
if err != nil {
    log.Fatalf("Failed to create client: %v", err)
}

The service gets many requests per second and I'm not sure if I should run the newClient() function only once on startup, or every time the API is called.

PS:
The same would go if another connector would be MySQL. Every time the API gets a request, the following code will run:

db, err = sql.Open("mysql", "yourusername:yourpassword@/yourdatabase")
if err != nil {
    panic(err.Error())    
}
  • 写回答

3条回答 默认 最新

  • dpfz27768 2017-05-02 21:23
    关注

    I'm not sure about datastore.Client, but database.DB manages a pool of connections, is safe for concurrent use, and you shouldn't really call db.Open every time you want to execute a query. In fact, the last paragraph from Open's documentation states that clearly.

    The returned DB is safe for concurrent use by multiple goroutines and maintains its own pool of idle connections. Thus, the Open function should be called just once. It is rarely necessary to close a DB.

    Update:

    If you take a look at the comment in the example code of the Basic Operations section in the datastore's documentation, you'll find the recommended use.

    Create a datastore client. In a typical application, you would create a single client which is reused for every datastore operation.

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

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据