PostgreSQL 流複製的主備切換
文章目錄
概述
流複製的主庫和備庫的角色不是靜態存在的,在維護過程中可以對二者進行角色切換。例如當主庫硬體故障或主庫需要調整引數需要重啟系統時,通常要進行流複製的主備切換。
如何判斷主備角色
在通常的主備架構下(一主多備,級聯除外)有以下五種方法判斷主備角色
-
1 作業系統上檢視wal傳送程序或wal接收執行緒
-
2 資料庫中檢視pg_stat_replication表
-
3 通過系統函式檢視
f說明是主庫,t說明是備庫
postgres=# select pg_is_in_recovery();
pg_is_in_recovery
-------------------
f
(1 row)
- 4 檢視資料庫控制資訊
通過pg_controldata命令,檢視 Database cluster state一欄
如果是in production ,說明是主庫
Database cluster state: in production
- 5 通過recovery.conf 檔案判斷
一般的,備庫才有recovery.conf,主庫一般沒有或是改名為recovery.done
檔案觸發方式切換
在備庫啟動時在 recovery.conf 檔案中加入一個觸發檔案的路徑(新加則需要重啟備庫)
trigger_file='/pgdata/.postgresql.trigger.2019'
關閉主庫
[[email protected]_PG9 pgdata]$ pg_ctl stop -m fast
waiting for server to shut down.... done
server stopped
在備庫上建立那個剛剛新加的檔案
[[email protected] pgdata]$ touch /pgdata/.postgresql.trigger.2019
可以看到備庫上的recovery檔案已經成為done了
-rw-rw-r--. 1 postgres postgres 239 Dec 25 21:50 recovery.done
此時備庫已經被啟用為主庫,可以直接做讀寫操作了
[[email protected] pgdata]$ pg_controldata |grep cluster
Database cluster state: in production
現在我們把原來的主庫當做備庫重新開始搭建主備,方法和之前一樣
準備recovery.conf檔案
指向原來的備庫,再重啟資料庫即可
pg_ctl promote方式切換
在檔案觸發方式下,需要配置引數和建立檔案,比較繁瑣。自PG9.1版本以後有了一個命令支援主備切換,就是pg_ctl promote命令
切換步驟如下:
1)關閉主庫,建議使用-m fast 模式關閉
2)在備庫上使用pg_ctl promote命令,直接將備庫切為主庫
3)在老主庫上配置recovery.conf 檔案,啟動
4)檢視主備狀態並檢視程序
如下:
[[email protected]_PG9 pgdata]$ pg_ctl promote
server promoting
[[email protected]_PG9 pgdata]$ pg_controldata |grep cluster
Database cluster state: in production
pg_rewind命令
首先我們先確認一下,使用這個命令的前提條件之一:
- postgresql.conf 配置檔案wal_log_hints引數值設為on
- 資料庫安裝時通過initdb初始化資料庫時使用了–data-checksums 選項
我們再來看一下這個命令的應用場景,在上述的兩種方式的切換中,第二步都是關閉原主庫,而且是強制關閉,因為關閉會有一個checkpoint的點。備庫同步完成後,兩邊的資料是同樣的一致性狀態。這樣原來的主很容易就能做新主的備庫
但是如果在執行的過程中忘記了關閉主庫,主庫一直處於執行狀態,那麼這個舊主和新主在資料時間線上就不是一致的了。就會導致後續搭建備庫失敗
這個命令就是通過新主去同步舊主,使這兩個庫處於一致性的狀態。類似於PG舊主的一次向前回滾。
是為了防止庫級別太大,重搭建庫過於麻煩。而出的一個命令
[[email protected]_PG9 pgdata]$ pg_rewind --help
pg_rewind resynchronizes a PostgreSQL cluster with another copy of the cluster.
Usage:
pg_rewind [OPTION]...
Options:
-D, --target-pgdata=DIRECTORY existing data directory to modify
--source-pgdata=DIRECTORY source data directory to synchronize with
--source-server=CONNSTR source server to synchronize with
-n, --dry-run stop before modifying anything
-P, --progress write progress messages
--debug write a lot of debug messages
-V, --version output version information, then exit
-?, --help show this help, then exit