设置SQL池中的最小空闲连接数。

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

Set minimum idle connections in SQL pool

问题

背景: 我想在我的Go应用程序中使用SQL数据库时减少响应时间。

Golang提供了一个带有连接池的SQL包。
它包括以下配置选项:

然而,没有像SetMinIdleConns这样的选项来确保总是有一些可用的打开连接可以在请求到来时使用。
因此,我的应用程序在负载下具有良好的响应时间,但在一段空闲时间后的第一个请求总是有一些延迟,因为它需要打开一个新的数据库连接。

问题: 有没有办法在Go标准库中解决这个问题,或者有没有其他带有这个功能的Go连接池库?

解决方法和已尝试的方法

  1. 我尝试将ConnMaxIdleTimeConnMaxLifetime设置为非常高的值,但然后SQL服务器会关闭它们,我在长时间空闲后的第一次调用中会遇到更高的延迟甚至错误。
  2. 显然,我可以创建一个定期使用数据库的后台任务。然而,这似乎不是一个干净的解决方案。
  3. 我正在考虑将另一种语言的连接池库移植到Go中。
英文:

Background: I want to reduce the response time when working with SQL databases in my Go applications.

Golang provides an SQL package with a connection pool.
It includes the following configuration options:

However, there is nothing like SetMinIdleConns to ensure that there are always some open connections that can be used when a request comes in.
As a result, my application has good response times under load, but the first request after some idle time always has some delay because it needs to open a new connection to the database.

Question: Is there a way to fix this with the Go standard library or is there some alternative connection pooling library for Go with this feature?

Workarounds and already tried:

  1. I tried setting ConnMaxIdleTime and ConnMaxLifetime to very high values, but then the SQL server closes them and I get even higher delays or even errors on the first call after a long idle time.
  2. Obviously, I could create a background task that periodically uses the database. However, this does not seem like a clean solution.
  3. I am considering porting a connection pool library from another language to Go.

答案1

得分: 0

pgx/pgxpool库提供了一个用于Postgres的连接池,可以配置最小连接数:

connConf, err := pgxpool.ParseConfig(connStr)
// ...(错误处理)
connConf.MaxConns = 50
// 设置最小连接数:
connConf.MinConns = 10
pool, err := pgxpool.ConnectConfig(context.TODO(), connConf)
英文:

The pgx/pgxpool library provides a connection pool for Postgres, which allows to configure the minimum number of connections:

    connConf, err := pgxpool.ParseConfig(connStr)
	// ... (error handling)
	connConf.MaxConns = 50
	// Set minimum number of connections:
    connConf.MinConns = 10
    pool, err := pgxpool.ConnectConfig(context.TODO(), connConf)

huangapple
  • 本文由 发表于 2021年8月5日 00:55:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/68655261.html
匿名

发表评论

匿名网友

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

确定