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

在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 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)