作者
digoal
日期
2020-02-14
标签
PostgreSQL , 负载均衡 , loadbalance , jdbc , druid , 只读负载均衡
背景
PG有多个只读节点时, 如何配置只读负载均衡? 注意这里说的不是对业务透明的读写分离.
方法1: 会话级负载均衡, lvs, haproxy均可.
《PostgreSQL HAProxy ha & load balance 代理》
《[未完待续] PostgreSQL 对等架构 负载均衡(HAProxy/LVS) 简明手册》
方法2: pgpool-ii 一步到位, 读写分离+负载均衡.
https://severalnines.com/database-blog/guide-pgpool-postgresql-part-one
并且pgpool支持踢出延迟高的只读实例.
https://www.pgpool.net/docs/latest/en/html/runtime-streaming-replication-check.html
Specifies the maximum tolerance level of replication delay in WAL bytes on the standby server against the primary server. If the delay exceeds this configured level, Pgpool-II stops sending the SELECT queries to the standby server and starts routing everything to the primary server even if load_balance_mode is enabled, until the standby catches-up with the primary. Setting this parameter to 0 disables the delay checking. This delay threshold check is performed every sr_check_period. Default is 0.
方法3: 驱动层实现会话级别负载均衡
《PostgreSQL libpq|jdbc 驱动层 load balance 与 failover》
druid 配置postgresql 驱动层读负载均衡
假设购买了多台阿里云rds pg只读实例, 需要在多台只读实例中实现负载均衡. 连接池使用的是druid.
到这里可以下载最新的pg jdbc驱动
https://jdbc.postgresql.org/
1 如何配置druid?
https://www.jianshu.com/p/27862528aa10
1.添加postgresql数据库连接驱动,compile("org.postgresql:postgresql:42.2.5"),这里假设最新版本为42.2.5
2.修改数据库驱动类名:driver-class-name: org.postgresql.Driver
3.修改数据库连接url为类似jdbc:postgresql://127.0.0.1:5432/postgres的格式,修改数据库连接的用户名和密码,其他不必修改
2 druid 通用配置
https://github.com/alibaba/druid/wiki/DruidDataSource%E9%85%8D%E7%BD%AE
DruidDataSource大部分属性都是参考DBCP的,如果你原来就是使用DBCP,迁移是十分方便的。
```
<property name="filters" value="stat" />
<property name="maxActive" value="20" />
<property name="initialSize" value="1" />
<property name="maxWait" value="60000" />
<property name="minIdle" value="1" />
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<property name="minEvictableIdleTimeMillis" value="300000" />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<property name="poolPreparedStatements" value="true" />
<property name="maxOpenPreparedStatements" value="20" />
<property name="asyncInit" value="true" />
```
在上面的配置中,通常你需要配置url、username、password,maxActive这三项。
Druid会自动跟url识别驱动类名,如果连接的数据库非常见数据库,配置属性driverClassName
asyncInit是1.1.4中新增加的配置,如果有initialSize数量较多时,打开会加快应用启动时间
3 如何配置druid 支持多个只读PG节点的负载均衡
https://jdbc.postgresql.org/documentation/head/connect.html#connection-parameters
只要把druid 配置里面的 url改成这样的格式, 并且使用最新版本的pg jdbc驱动(因为老版本的pg jdbc可能还没有支持多host配置)即可:
jdbc:postgresql://host_ro1:port1,host_ro2:port2/db123?targetServerType=slave&loadBalanceHosts=true
PostgreSQL 许愿链接
您的愿望将传达给PG kernel hacker、数据库厂商等, 帮助提高数据库产品质量和功能, 说不定下一个PG版本就有您提出的功能点. 针对非常好的提议,奖励限量版PG文化衫、纪念品、贴纸、PG热门书籍等,奖品丰富,快来许愿。开不开森.
9.9元购买3个月阿里云RDS PostgreSQL实例
PostgreSQL 解决方案集合
德哥 / digoal's github - 公益是一辈子的事.





