概述
流複制的主庫和備庫的角色不是靜态存在的,在維護過程中可以對二者進行角色切換。例如當主庫硬體故障或主庫需要調整參數需要重新開機系統時,通常要進行流複制的主備切換。
如何判斷主備角色
在通常的主備架構下(一主多備,級聯除外)有以下五種方法判斷主備角色
- 作業系統上檢視wal發送程序或wal接收線程
- 資料庫中檢視pg_stat_replication表
-
通過系統函數檢視
f說明是主庫,t說明是備庫
postgres=# select pg_is_in_recovery();
pg_is_in_recovery
-------------------
f
(1 row)
-
檢視資料庫控制資訊
通過pg_controldata指令,檢視 Database cluster state一欄
如果是in production ,說明是主庫
Database cluster state: in production
-
通過recovery.conf 檔案判斷
一般的,備庫才有recovery.conf,主庫一般沒有或是改名為recovery.done
檔案觸發方式切換
在備庫啟動時在 recovery.conf 檔案中加入一個觸發檔案的路徑(新加則需要重新開機備庫)
trigger_file='/pgdata/.postgresql.trigger.2019'
關閉主庫
[postgres@GuangFa_PG9 pgdata]$ pg_ctl stop -m fast
waiting for server to shut down.... done
server stopped
在備庫上建立那個剛剛新加的檔案
[postgres@localhost pgdata]$ touch /pgdata/.postgresql.trigger.2019
可以看到備庫上的recovery檔案已經成為done了
-rw-rw-r--. 1 postgres postgres 239 Dec 25 21:50 recovery.done
此時備庫已經被激活為主庫,可以直接做讀寫操作了
[postgres@localhost 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)檢視主備狀态并檢視程序
如下:
[postgres@GuangFa_PG9 pgdata]$ pg_ctl promote
server promoting
[postgres@GuangFa_PG9 pgdata]$ pg_controldata |grep cluster
Database cluster state: in production
pg_rewind指令
首先我們先确認一下,使用這個指令的前提條件之一:
- postgresql.conf 配置檔案wal_log_hints參數值設為on
- 資料庫安裝時通過initdb初始化資料庫時使用了--data-checksums 選項
我們再來看一下這個指令的應用場景,在上述的兩種方式的切換中,第二步都是關閉原主庫,而且是強制關閉,因為關閉會有一個checkpoint的點。備庫同步完成後,兩邊的資料是同樣的一緻性狀态。這樣原來的主很容易就能做新主的備庫
但是如果在執行的過程中忘記了關閉主庫,主庫一直處于運作狀态,那麼這個舊主和新主在資料時間線上就不是一緻的了。就會導緻後續搭建備庫失敗
這個指令就是通過新主去同步舊主,使這兩個庫處于一緻性的狀态。類似于PG舊主的一次向前復原。
是為了防止庫級别太大,重搭建庫過于麻煩。而出的一個指令
[postgres@GuangFa_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