如何获取 Golang 数据库连接池来管理集群中多台主机的连接?

How do I get a Golang Database connection pool to manage connections to multiple hosts in a cluster?

我正在设置 bi-direction replication between four PostgreSQL workers, and I'd like to have my Go database connection pool handle connections to all four. It ought to be able to create multiple connections to them all, randomly select one for any given query, and fail over when a connection drops. Is this doable in the Go database library? Or should I just use pgBouncer and not try to get database/sql or pgx 来处理这种平衡?

golang 中的连接池在您调用 sql.Open(driverName, dataSourceName) 时创建,其中 dataSourceName 是特定于驱动程序的 configuration 用于连接到数据库。每当我们更改 configuration(即更改主机地址、架构、用户名等)时,我们都需要打开新连接,因此将创建新的连接池。如果一个驱动程序可以处理负载平衡,它应该在 dataSourceName 中是可配置的,例如如 MariaDB Connector/J 高可用性配置。

据我所知,lib/pq and pgx 尚不支持负载平衡。在您的情况下,要连接到集群中的数据库服务器,您需要为每个服务器打开不同的连接池,然后手动管理连接(并执行负载平衡)。这种方法需要做很多工作。我觉得用pgBouncer比较好