英文:
Set minimum idle connections in SQL pool
问题
背景: 我想在我的Go应用程序中使用SQL数据库时减少响应时间。
Golang提供了一个带有连接池的SQL包。
它包括以下配置选项:
- func (db *DB) SetConnMaxIdleTime(d time.Duration)
- func (db *DB) SetConnMaxLifetime(d time.Duration)
- func (db *DB) SetMaxIdleConns(n int)
- func (db *DB) SetMaxOpenConns(n int)
然而,没有像SetMinIdleConns
这样的选项来确保总是有一些可用的打开连接可以在请求到来时使用。
因此,我的应用程序在负载下具有良好的响应时间,但在一段空闲时间后的第一个请求总是有一些延迟,因为它需要打开一个新的数据库连接。
问题: 有没有办法在Go标准库中解决这个问题,或者有没有其他带有这个功能的Go连接池库?
解决方法和已尝试的方法:
- 我尝试将
ConnMaxIdleTime
和ConnMaxLifetime
设置为非常高的值,但然后SQL服务器会关闭它们,我在长时间空闲后的第一次调用中会遇到更高的延迟甚至错误。 - 显然,我可以创建一个定期使用数据库的后台任务。然而,这似乎不是一个干净的解决方案。
- 我正在考虑将另一种语言的连接池库移植到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:
- func (db *DB) SetConnMaxIdleTime(d time.Duration)
- func (db *DB) SetConnMaxLifetime(d time.Duration)
- func (db *DB) SetMaxIdleConns(n int)
- func (db *DB) SetMaxOpenConns(n int)
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:
- I tried setting
ConnMaxIdleTime
andConnMaxLifetime
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. - Obviously, I could create a background task that periodically uses the database. However, this does not seem like a clean solution.
- 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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论