在启动时创建默认数量的数据库连接(Golang)

huangapple go评论77阅读模式
英文:

create a default number of db connections at startup golang

问题

我希望在应用程序启动时始终有一些空闲的数据库连接。

在Golang中,我只看到MaxIdleConnsMaxOpenConns这两个选项。
我没有看到任何setMinIdle函数。
感谢您的帮助。

英文:

I want some idle db connections to always there on application startup.

I can only see MaxIdleConns and MaxOpenConns in Golang.
I don't see any setMinIdle func.
Help is appreciated.

答案1

得分: 1

为了解决你的问题,你可以在将应用程序标记为已启动之前,迭代一定次数并对数据库进行并行请求(例如用于k8s的就绪探针)。

一般来说,在选择连接池配置时,有几个要考虑的因素:

  1. 默认情况下,没有打开连接的限制,因此如果出现错误或意外的大量请求涌入,可能会对数据库产生影响。这就是为什么应该设置SetMaxOpenConns
  2. 如果连接将永远存在,也不是最理想的情况。因为它们会占用内存和数据库资源。所以要设置SetMaxIdleConns,记住,默认值是2

在生产环境中,常见的做法是将数据库连接池的MaxOpenConns设置为一个限制值,该值取决于每秒预期的请求、工作线程数和数据库的配置。至于MaxIdleConns,应该设置为MaxOpenConns的一小部分,考虑同时请求的分散程度。例如,可以设置为MaxOpenConns的25%或50%。

英文:

To target the main part of your question, you could iterate a decided number of times and make a parallel request to your database before marking your app as started. (For instance for k8s readiness probe).

In general, when selecting a configuration for the connection pool configuration, there are few things to consider:

  1. By default, no limit of open connections is present, thus if some bug occurs or an unexpected high influx of incoming requests, it may be impactful for DB. That's why one should set SetMaxOpenConns.
  2. If connections will live forever, it's also not the very best situation. As they take memory and DB resources. So - set SetMaxIdleConns, remember, it's default value is 2.

The common practice for a production-grade setup is to set the DB connection pool to have a limit on MaxOpenConns, which depends on expected requests per second, number of workers and configuration of the database. As for MaxIdleConns — it should be set to a fraction of MaxOpenConns, consider set your expectation on what's the dispersion of simultaneous requests. Like 25 % or 50% of MaxOpenConns.

huangapple
  • 本文由 发表于 2021年9月17日 17:39:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/69221146.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定