共計 1989 個字符,預計需要花費 5 分鐘才能閱讀完成。
本篇內容介紹了“PostgreSQL 中 Failover 的配置方法是什么”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓丸趣 TV 小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
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 的配置方法是什么”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注丸趣 TV 網站,丸趣 TV 小編將為大家輸出更多高質量的實用文章!