PostgreSQL jdbc 9.4 支持load balance 和 connection failover了

1 minute read

背景

好消息,PostgreSQL的jdbc驱动支持load balance 和 connection failover了。

通过配置多对主机和端口的信息,可以实现简单的连接FALIOVER,直到取到一个正常的连接为止。

Connection Fail-over

To support simple connection fail-over it is possible to define multiple endpoints (host and port pairs) in the connection url separated by commas. The driver will try to once connect to each of them in order until the connection succeeds. If none succeed, a normal connection exception is thrown.

The syntax for the connection url is:

jdbc:postgresql://host1:port1,host2:port2/database  

The simple connection fail-over is useful when running against a high availability postgres installation that has identical data on each node. For example streaming replication postgres or postgres-xc cluster.

For example an application can create two connection pools. One data source is for writes, another for reads.

结合targetServerType,可以非常方便的实现负载均衡,对于读写数据源,配置为master,

对于只读数据源可以配置为preferSlave或者slave。

The write pool limits connections only to master node:

jdbc:postgresql://node1,node2,node3/accounting?targetServerType=master .   

And read pool balances connections between slaves nodes, but allows connections also to master if no slaves are available:

jdbc:postgresql://node1,node2,node3/accounting?targetServerType=preferSlave&loadBalanceHosts=true  

targetServerType

Allows opening connections to only servers with required state, the allowed values are any, master, slave and preferSlave. The master/slave distinction is currently done by observing if the server allows writes. The value preferSlave tries to connect to slaves if any are available, otherwise allows falls back to connecting also to master.

loadBalanceHosts = boolean

In default mode (disabled) hosts are connected in the given order. If enabled hosts are chosen randomly from the set of suitable candidates.

使用这种方法的好处大大滴,举个例子:

node1,node2,node3使用流复制组成了一主2备的环境,其中有一个VIP,对应到主节点,所有的recover.conf都指向这个VIP。(这个VIP只是方便recover.conf的统一性,其实jdbc的failover和load balance都不依赖它)

然后我们在配置jdbc时,只需要配置2个数据源,一个对应master一个对应preferSlave。

需要写操作时,指定master的数据源,需要读操作时,使用preferSlave的数据源。

那么JDBC是怎么判断数据源的类型的呢?

其实很简单,数据库提供了pg_is_in_recovery()函数,true就是slave, false就是master。jdbc应该就是用它来判断的。

(pgpool-II也是这么干的)

jdbc-HA比pgpool-II只差了自动的读写分离这个功能,但是这块在应用层其实很好控制,开发应用时,大家保持好配置2个数据源的这个姿势吧。

或者你可以把jdbc9.4和plproxy,或者pg-xc的coordinator节点结合来使用,实现完全的负载均衡和failover。

因为plproxy节点和coordinator节点都是对等节点,所以非常适合用来做负载均衡,以前我们可能需要结合LVS来达到类似的目的,有了jdbc 9.4不需要了。

参考

1. https://jdbc.postgresql.org/documentation/94/connect.html#connection-parameters

2. http://ha-jdbc.github.io/

Flag Counter

digoal’s 大量PostgreSQL文章入口