PostgreSQL中Failover的配置方法是什么

本篇内容介绍了“PostgreSQL中Failover的配置方法是什么”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

PostgreSQL 10+的libpq版本提供了Seamless Application Failover功能,在连接PG的时候可指定多个目标库并指定target_session_attrs属性(read-write、any、read-only),libpq可根据目标库的状态分发/切换到不同的数据库上。
举个例子,比如现在在26.28:5433和26.26:5432上有两个PG实例,两个实例均可对外提供读写,Failover的配置如下:
1.read-write/any

[xdb@localhost ~]$ psql 'postgres://192.168.26.26:5432,192.168.26.28:5433/postgres?target_session_attrs=read-write' -U xdb -c "select inet_server_addr()"
Timing is on.
Expanded display is used automatically.
 inet_server_addr 
------------------
 192.168.26.26
(1 row)
Time: 2.439 ms
[xdb@localhost ~]$

连接到第一个匹配的实例上。关闭26.26上的pg,重新连接,会自动切换到26.28上的pg上。

[xdb@localhost ~]$ pg_ctl stop
waiting for server to shut down.... done
server stopped
[xdb@localhost ~]$ 
[xdb@localhost ~]$ psql 'postgres://192.168.26.26:5432,192.168.26.28:5433/postgres?target_session_attrs=read-write' -U xdb -c "select inet_server_addr()"
Timing is on.
Expanded display is used automatically.
 inet_server_addr 
------------------
 192.168.26.28
(1 row)
Time: 0.837 ms
[xdb@localhost ~]$

搭建主从流复制环境,一个主库一个备库,分别是26.28和26.25

[xdb@localhost ~]$ psql 'postgres://192.168.26.25:5432,192.168.26.28:5432/postgres?target_session_attrs=read-write' -c "select inet_server_addr()" -U pg12
Password for user pg12: 
 inet_server_addr 
------------------
 192.168.26.28
(1 row)
[xdb@localhost ~]$ psql 'postgres://192.168.26.25:5432,192.168.26.28:5432/postgres?target_session_attrs=any' -c "select inet_server_addr()" -U pg12
Password for user pg12: 
 inet_server_addr 
------------------
 192.168.26.25
(1 row)

使用read-write选项会自动连接到主库上,而使用any选项,则会根据顺序优先连接到从库上。

2.read-only
把连接属性改为其他,如read-only

[xdb@localhost ~]$ psql 'postgres://192.168.26.26:5432,192.168.26.28:5433/postgres?target_session_attrs=read-only' -U xdb -c "select inet_server_addr()"
psql: invalid target_session_attrs value: "read-only"
[xdb@localhost ~]$

提示无效的属性值,实际上只支持read-write和any两个选项。

“PostgreSQL中Failover的配置方法是什么”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注网站,小编将为大家输出更多高质量的实用文章!