前言
❝PostgreSQL在9.x之後引入了主從的流複製機制,流複製同步方式有同步、異步兩種
1.主從流複製介紹
在流複製中,三種類型的進程協同工作:
1.主服務器上的walsender進程將WAL(預寫日誌)數據發送到備用服務器。
2.備用服務器上的walreceiver進程接收並重放WAL數據。
3.備用服務器上的啓動進程啓動walreceiver進程。
walsender和walreceiver使用單個TCP連接進行通信。
2.主庫白名單設置
su - postgres
cat > $PGDATA/pg_hba.conf << EOF
# TYPE DATABASE USER ADDRESS METHOD
local all all trust
host all all 127.0.0.1/32 trust
host all all 0.0.0.0/0 md5
host replication all 0.0.0.0/0 md5
local replication all trust
EOF
3.主庫開歸檔
[root@primary ~]# mkdir -p /var/lib/pgsql/archive
[root@primary ~]# chown -R postgres.postgres /var/lib/pgsql/archive
su - postgres
cat >> $PGDATA/postgresql.conf <<"EOF"
wal_level='replica'
archive_mode='on'
archive_command='test ! -f /var/lib/pgsql/archive/%f && cp %p /var/lib/pgsql/archive/%f'
restore_command='cp /var/lib/pgsql/archive/%f %p'
max_wal_senders=10
EOF
4.主庫創建複製用戶
create role repladm login encrypted
password 'replica' replication;
5.從庫對主庫備份
mkdir -p /backup
chown postgres:postgres /backup
su - postgres
pg_basebackup -h 192.168.6.20 -p 5432 -U repladm -l bk20240411 -F p -P -R -D /backup
執行完成後,從庫會產生文件standby.signal,如下:
6.還原從庫
關閉從庫,刪除從庫的數據文件,並且將備份文件覆蓋從庫的數據文件
[postgres@standby01 ~]$echo $PGDATA
/pgccc/pgdata
[postgres@standby01 ~]$ rm -rf /pgccc/pgdata/*
[postgres@standby01 ~]$ cp -r /backup/* /pgccc/pgdata/*
修改從庫primary_conninfo參數
cat >> $PGDATA/postgresql.conf <<"EOF"
primary_conninfo = 'host=192.168.6.20 port=5432 user=repladm password=replica'
EOF
重啓備庫
[postgres@standby01 ~]$ pg_ctl start
7.主從狀態
--主庫查看wal日誌發送狀態
select * from pg_stat_replication;
--從庫查看wal日誌接收狀態
select * from pg_stat_wal_receiver;
8.主從複製同步測試
8.1 主庫插入
postgres=# create table test(id int,info text);
postgres=# insert into test select n,'test'
from generate_series(1,2000) as n;
8.2 從庫驗證
9.總結
❝本文詳細介紹了物理複製(流複製)的搭建,可以從實例級複製出一個與主庫一模一樣的實例級的從庫
轉自
挺好看的一位實習生,PG主流從搭建的如此666
https://mp.weixin.qq.com/s?__biz=MzI3OTE0NDIyNw==&mid=2247493015&idx=1&sn=926a9948af0690936b5f6cb0a9d2eb20&chksm=eaf984ffb0ce66de6f2017a8f0bdd8c9ed790ca6f849f357f8743c2bd02c253488e99fbce642&scene=132&exptype=timeline_recommend_article_extendread_samebiz&show_related_article=1&subscene=0&scene=132#wechat_redirect
踩了一堆坑,終於掌握了PG主從流的精髓
https://mp.weixin.qq.com/s/ji-umytSocYDcx2CMYBOEg