PostgreSQL 10.0 preview 功能增强 - libpq支持多主机连接(failover,LB)让数据库HA和应用配合更紧密

本文涉及的产品
RDS AI 助手,专业版
RDS MySQL DuckDB 分析主实例,集群系列 4核8GB
简介:

标签

PostgreSQL , 10.0 , libpq , jdbc , failover , loadbalance , multi host , target_session_attrs


背景

数据库一主多备,这个词在互联网应该不陌生。但是主备切换和应用程序如何配合才能天衣无缝呢?你可能会有这样的疑问。

1. 什么类型的QUERY发给主库,什么类型的QUERY发给备库?

2. 主库和备库发生了角色切换之后,客户端连接如何配合?

业界有一些做法可以回答这两个问题。

1. 通常使用集群软件,使用VIP来表示主备库的角色,不管怎么切换,VIP1永远都是主库,VIP2永远都是备库。

对于客户端来说,通过VIP来判断是主库还是备库,程序自己控制哪些SQL发给主库,哪些SQL发给备库。

一个典型的例子

https://github.com/digoal/PostgreSQL_HA_with_primary_standby_2vip

2. 使用VIP是让数据库和应用程序形成默契的一种方法,还有没有更好的方法呢?比如数据库驱动层能不能配合角色的判断?

Oracle做得不错,Oracle的客户端,可以配合RAC,自动识别failover, switchover。

PostgreSQL jdbc驱动,也实现了类似的功能,支持failover, loadbalance。

https://jdbc.postgresql.org/documentation/94/connect.html

PostgreSQL jdbc相关参数如下

1.

targetServerType = {any, master, slave, preferSlave}  
  
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.  
  
any表示连接到任意节点  
preferSlave表示优先连接到slave节点  
master或slave表示连接到master或slave节点。  

2.

hostRecheckSeconds = int  
  
Controls how long in seconds the knowledge about a host state is cached in JVM wide global cache.   
The default value is 10 seconds.  
  
重新检测节点状态的时间间隔  

3.

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.  
  
是否随机选择节点,负载均衡  

4.

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.  
  
当配置了多个目标节点时,JDBC会按顺序连接目标,直到连接成功为止。  
  
jdbc连接串语法  
  
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.  

5.

典型的例子,应用程序可以配置两个连接池,一个配置为master,写请求发往这个连接池。另一个配置为slave优先,同时开启负载均衡参数,读请求发往这个连接池。

For example an application can create two connection pools.   
One data source is for writes, another for reads.   
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  

PostgreSQL 10.0 libpq增加多个连接的功能

PostgreSQL 10.0 libpq层,也增加了多连接功能,设计时引入了target_session_attrs参数,可以设置为read-write或者any。不同的target_session_attrs配置,对应不同的节点检测机制。

target_session_attrs=read-write,使用show transaction_read_only检测节点,返回on,表示这是只读节点,off表示这是可读写节点。(standby返回on, 同时通过default_transaction_read_only可以让master也返回on)。

target_session_attrs=any,表示不检测。

两个patch的commit信息如下。

libpq: Allow connection strings and URIs to specify multiple hosts.  
  
author	Robert Haas <rhaas@postgresql.org>	  
Thu, 3 Nov 2016 21:25:20 +0800 (09:25 -0400)  
committer	Robert Haas <rhaas@postgresql.org>	  
Thu, 3 Nov 2016 21:25:20 +0800 (09:25 -0400)  
commit	274bb2b3857cc987cfa21d14775cae9b0dababa5  
tree	488b5fd46e2cb4acdab7fb2dd30c4e4d1d4bb7d1	tree | snapshot  
parent	770671062f130a830aa89100c9aa2d26f8d4bf32	commit | diff  
libpq: Allow connection strings and URIs to specify multiple hosts.  
  
It's also possible to specify a separate port for each host.  
  
Previously, we'd loop over every address returned by looking up the  
host name; now, we'll try every address for every host name.  
  
Patch by me.  Victor Wagner wrote an earlier patch for this feature,  
which I read, but I didn't use any of his code.  Review by Mithun Cy.  
libpq: Add target_session_attrs parameter.  
  
author	Robert Haas <rhaas@postgresql.org>	  
Wed, 30 Nov 2016 01:18:31 +0800 (12:18 -0500)  
committer	Robert Haas <rhaas@postgresql.org>	  
Wed, 30 Nov 2016 01:18:31 +0800 (12:18 -0500)  
Commit 274bb2b3857cc987cfa21d14775cae9b0dababa5 made it possible to  
specify multiple IPs in a connection string, but that's not good  
enough for the case where you have a read-write master and a bunch of  
read-only standbys and want to connect to whichever server is the  
master at the current time.  This commit allows that, by making it  
possible to specify target_session_attrs=read-write as a connection  
parameter.  
  
There was extensive discussion of the best name for the connection  
parameter and its values as well as the best way to distinguish master  
and standbys.  For now, adopt the same solution as JDBC: if the user  
wants a read-write connection, issue 'show transaction_read_only' and  
rejection the connection if the result is 'on'.  In the future, we  
could add additional values of this new target_session_attrs parameter  
that issue different queries; or we might have some way of  
distinguishing the server type without resorting to an SQL query; but  
right now, we have this, and that's (hopefully) a good start.  
  
Victor Wagner and Mithun Cy.  Design review by Álvaro Herrera, Catalin  
Iacob, Takayuki Tsunakawa, and Craig Ringer; code review by me.  I  
changed Mithun's patch to skip all remaining IPs for a host if we  
reject a connection based on this new parameter, rewrote the  
documentation, and did some other cosmetic cleanup.  
  
Discussion: http://postgr.es/m/CAD__OuhqPRGpcsfwPHz_PDqAGkoqS1UvnUnOnAB-LBWBW=wu4A@mail.gmail.com  

libpq用法介绍

URI格式

postgresql://[user[:password]@][netloc][:port][,...][/dbname][?param1=value1&...]  
  
postgresql://  
postgresql://localhost  
postgresql://localhost:5433  
postgresql://localhost/mydb  
postgresql://user@localhost  
postgresql://user:secret@localhost  
postgresql://other@localhost/otherdb?connect_timeout=10&application_name=myapp  
postgresql://host1:123,host2:456/somedb?target_session_attrs=any&application_name=myapp  

配置多个目标节点,host:port使用逗号隔开即可。

host  
  
Comma-separated list of host names.   
If a host name begins with a slash, it specifies Unix-domain communication rather than TCP/IP communication;   
the value is the name of the directory in which the socket file is stored.   
If multiple host names are specified, each will be tried in turn in the order given.   
The default behavior when host is not specified is to connect to a Unix-domain socket in /tmp (or whatever socket directory was specified when PostgreSQL was built).   
On machines without Unix-domain sockets, the default is to connect to localhost.  
  
port  
  
Port number to connect to at the server host, or socket file name extension for Unix-domain connections.   
If the host parameter included multiple, comma-separated hosts, this parameter may specify a list of ports of equal length,   
or it may specify a single port number to be used for all hosts.  
  
target_session_attrs  
  
If this parameter is set to read-write, only a connection in which read-write transactions are accepted by default is considered acceptable.   
The query show transaction_read_only will be sent upon any successful connection;   
if it returns on, the connection will be closed.   
If multiple hosts were specified in the connection string, any remaining servers will be tried just as if the connection attempt had failed.   
The default value of this parameter, any, regards all connections as acceptable.  

使用libpq,你同样可以实现与jdbc一样的效果(负载均衡,自动找到master)。

HA只需要负责切换角色,不需要再负责切换IP地址了。可以更省心一些。

这个patch的讨论,详见邮件组,本文末尾URL。

PostgreSQL社区的作风非常严谨,一个patch可能在邮件组中讨论几个月甚至几年,根据大家的意见反复的修正,patch合并到master已经非常成熟,所以PostgreSQL的稳定性也是远近闻名的。

参考

https://git.postgresql.org/gitweb/?p=postgresql.git;a=commit;h=274bb2b3857cc987cfa21d14775cae9b0dababa5

https://git.postgresql.org/gitweb/?p=postgresql.git;a=commitdiff;h=721f7bd3cbccaf8c07cad2707826b83f84694832

https://www.postgresql.org/docs/devel/static/libpq-connect.html#libpq-connstring

https://jdbc.postgresql.org/documentation/94/connect.html

相关实践学习
使用PolarDB和ECS搭建门户网站
本场景主要介绍如何基于PolarDB和ECS实现搭建门户网站。
阿里云数据库产品家族及特性
阿里云智能数据库产品团队一直致力于不断健全产品体系,提升产品性能,打磨产品功能,从而帮助客户实现更加极致的弹性能力、具备更强的扩展能力、并利用云设施进一步降低企业成本。以云原生+分布式为核心技术抓手,打造以自研的在线事务型(OLTP)数据库Polar DB和在线分析型(OLAP)数据库Analytic DB为代表的新一代企业级云原生数据库产品体系, 结合NoSQL数据库、数据库生态工具、云原生智能化数据库管控平台,为阿里巴巴经济体以及各个行业的企业客户和开发者提供从公共云到混合云再到私有云的完整解决方案,提供基于云基础设施进行数据从处理、到存储、再到计算与分析的一体化解决方案。本节课带你了解阿里云数据库产品家族及特性。
目录
相关文章
|
4月前
|
SQL 关系型数据库 MySQL
阿里云RDS云数据库全解析:产品功能、收费标准与活动参考
与云服务器ECS一样,关系型数据库RDS也是很多用户上云必买的热门云产品之一,阿里云的云数据库RDS主要包含RDS MySQL、RDS SQL Server、RDS PostgreSQL、RDS MariaDB等几个关系型数据库,并且提供了容灾、备份、恢复、监控、迁移等方面的全套解决方案,帮助您解决数据库运维的烦恼。本文为大家介绍阿里云的云数据库 RDS主要产品及计费方式、收费标准以及活动等相关情况,以供参考。
|
4月前
|
存储 人工智能 NoSQL
AI大模型应用实践 八:如何通过RAG数据库实现大模型的私有化定制与优化
RAG技术通过融合外部知识库与大模型,实现知识动态更新与私有化定制,解决大模型知识固化、幻觉及数据安全难题。本文详解RAG原理、数据库选型(向量库、图库、知识图谱、混合架构)及应用场景,助力企业高效构建安全、可解释的智能系统。
|
5月前
|
SQL Java 关系型数据库
Java连接MySQL数据库环境设置指南
请注意,在实际部署时应该避免将敏感信息(如用户名和密码)硬编码在源码文件里面;应该使用配置文件或者环境变量等更为安全可靠地方式管理这些信息。此外,在处理大量数据时考虑使用PreparedStatement而不是Statement可以提高性能并防止SQL注入攻击;同时也要注意正确处理异常情况,并且确保所有打开过得资源都被正确关闭释放掉以防止内存泄漏等问题发生。
215 13
|
5月前
|
SQL 关系型数据库 MySQL
MySQL数据库连接过多(Too many connections)错误处理策略
综上所述,“Too many connections”错误处理策略涉及从具体参数配置到代码层面再到系统与架构设计全方位考量与改进。每项措施都需根据具体环境进行定制化调整,并且在执行任何变更前建议先行测试评估可能带来影响。
1396 11
|
5月前
|
存储 弹性计算 Cloud Native
云原生数据库的演进与应用实践
随着企业业务扩展,传统数据库难以应对高并发与弹性需求。云原生数据库应运而生,具备计算存储分离、弹性伸缩、高可用等核心特性,广泛应用于电商、金融、物联网等场景。阿里云PolarDB、Lindorm等产品已形成完善生态,助力企业高效处理数据。未来,AI驱动、Serverless与多云兼容将推动其进一步发展。
259 8
|
5月前
|
存储 弹性计算 安全
现有数据库系统中应用加密技术的不同之处
本文介绍了数据库加密技术的种类及其在不同应用场景下的安全防护能力,包括云盘加密、透明数据加密(TDE)和选择列加密。分析了数据库面临的安全威胁,如管理员攻击、网络监听、绕过数据库访问等,并通过能力矩阵对比了各类加密技术的安全防护范围、加密粒度、业务影响及性能损耗。帮助用户根据安全需求、业务改造成本和性能要求,选择合适的加密方案,保障数据存储与传输安全。
|
6月前
|
存储 人工智能 数据库
视图是什么?为什么要用视图呢?数据库视图:定义、特点与应用
本文三桥君深入探讨数据库视图的概念与应用,从定义特点到实际价值全面解析。视图作为虚拟表具备动态更新、简化查询、数据安全等优势,能实现多角度数据展示并保持数据库重构的灵活性。产品专家三桥君还分析了视图与基表关系、创建维护要点及性能影响,强调视图是提升数据库管理效率的重要工具。三桥君通过系统讲解,帮助读者掌握这一常被忽视却功能强大的数据库特性。
1632 0
|
8月前
|
存储 关系型数据库 测试技术
拯救海量数据:PostgreSQL分区表性能优化实战手册(附压测对比)
本文深入解析PostgreSQL分区表的核心原理与优化策略,涵盖性能痛点、实战案例及压测对比。首先阐述分区表作为继承表+路由规则的逻辑封装,分析分区裁剪失效、全局索引膨胀和VACUUM堆积三大性能杀手,并通过电商订单表崩溃事件说明旧分区维护的重要性。接着提出四维设计法优化分区策略,包括时间范围分区黄金法则与自动化维护体系。同时对比局部索引与全局索引性能,展示后者在特定场景下的优势。进一步探讨并行查询优化、冷热数据分层存储及故障复盘,解决分区锁竞争问题。
1027 2

相关产品

  • 云原生数据库 PolarDB
  • 云数据库 RDS PostgreSQL 版