如何在 Golang 中使用数据库连接池来管理连接到多个集群主机的连接?

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

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

问题

我正在为四个PostgreSQL工作节点设置双向复制,我希望我的Go数据库连接池能够处理所有四个节点的连接。它应该能够创建多个连接,并在每次查询时随机选择一个节点,并在连接断开时进行故障转移。在Go数据库库中是否可以实现这一点?或者我应该只使用pgBouncer,而不尝试让database/sqlpgx来处理负载均衡?

英文:

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/pqpgx目前还不支持负载均衡。在你的情况下,要连接到集群中的数据库服务器,你需要为每个服务器打开不同的连接池,然后手动管理连接(并执行负载均衡)。这种方法需要做很多工作。我认为使用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.

huangapple
  • 本文由 发表于 2017年4月25日 07:23:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/43599172.html
匿名

发表评论

匿名网友

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

确定