英文:
How do I get a Golang Database connection pool to manage connections to multiple hosts in a cluster?
问题
我正在为四个PostgreSQL工作节点设置双向复制,我希望我的Go数据库连接池能够处理所有四个节点的连接。它应该能够创建多个连接,并在每次查询时随机选择一个节点,并在连接断开时进行故障转移。在Go数据库库中是否可以实现这一点?或者我应该只使用pgBouncer,而不尝试让database/sql或pgx来处理负载均衡?
英文:
I'm setting up 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 to handle that balancing?
答案1
得分: 5
在golang中,每当调用sql.Open(driverName, dataSourceName)
时,都会创建一个连接池。其中,dataSourceName
是用于连接数据库的特定于驱动程序的配置。每当我们更改配置(例如更改主机地址、模式、用户名等),我们需要打开新的连接,从而创建新的连接池。如果驱动程序可以处理负载均衡,那么它应该可以在dataSourceName
中进行配置,例如MariaDB Connector/J中的高可用配置。
据我所知,lib/pq和pgx目前还不支持负载均衡。在你的情况下,要连接到集群中的数据库服务器,你需要为每个服务器打开不同的连接池,然后手动管理连接(并执行负载均衡)。这种方法需要做很多工作。我认为使用pgBouncer会更好一些。
英文:
Connection pool in golang is created whenever you call sql.Open(driverName, dataSourceName)
, where dataSourceName
is driver specific configuration
for connecting to database. Whenever we change the configuration
(i.e. changing host address, schema, username, etc) we need to open new connection, thus new connection pool will be created. If a driver can handle load balancing, it should be configurable in dataSourceName
, e.g. as in MariaDB Connector/J high availability configuration.
AFAIK, load balancing not yet supported in lib/pq and pgx. In your case, to connect to database servers in cluster, you need to open different connection pool for each server, then manage the connections (and perform load balancing) manually. This approach needs a lot of work to be done. I think it is better to use pgBouncer.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论