dqrnskni67375 2017-05-02 21:09
浏览 1685


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.

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 {
  • 写回答

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.


    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.

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



  • ¥15 电脑开机过商标后就直接这样,求解各位
  • ¥15 mysql , 用自己创建的本地主机和用户名 登录不上
  • ¥15 关于#web项目#的问题,请各位专家解答!
  • ¥15 vmtools环境不正常
  • ¥15 请问如何在Ubuntu系统中安装使用microsoft R open?
  • ¥15 jupyter notebook
  • ¥30 informer时间序列预测
  • ¥20 SSR引物多态性分析
  • ¥15 大漠插件在Win11易语言注册调用和免注册灵异事件,VS上注册调用完全没问题
  • ¥15 Addressable缓存机制做热更新的问题