Postgres 主从配置(四)

Postgres 主从切换

数据库主从结构中由从库升级为主库较为容易些,但是主库恢复后重新加入到主从结构中就不那么容易了。
以往的做法是当成一个全新的从库加入进来,数据需要重新从现有的主库中使用pg_backup全部拉取过来,数据量少时还可以接受,如果数据量过大对现有系统的影响很大,
而且也非常耗时。与全量拉取数据比较,其实在本地已经存在大部分的数据内容,用没有方法使用增量的方式呢?充分利用已有数据。类似于rsync
pg_rewind 会将目标库的数据文件,配置文件复制到本地目录,由于 pg_rewind 不会读取所有未发生变化的数据块,所以速度比重做备库要快很多。

环境

db1 10.1.88.47 主库
db2 10.1.88.46 从库

备注:流复制环境参考 PostgreSQL:使用 pg_basebackup 搭建流复制环境 , 本文略。

--pg_rewind 前提条件
1 full_page_writes
2 wal_log_hints 设置成 on 或者 PG 在初始化时开启 checksums 功能
需要重新启动Postgres


从库切换为主库 db2为新的主库
$pg_ctl promote -D $PGDATA
server promoting

在db2上建立新表并插入数据
$psql
psql (9.5alpha1)
Type "help" for help.

postgres=# create table test_2(id int4);
CREATE TABLE

postgres=# insert into test_2(id) select n from generate_series(1,10000) n;
INSERT 0 10000

停主库

$pg_ctl stop -m fast -D $PGDATA
waiting for server to shut down....... done
server stopped

备注:停完原主库后,千万不能立即以备节点形式拉起老库,否则在执行 pg_rewind 时会报,"target server must be shut down cleanly" 错误。

使用pg_rewind差分同步数据
$/usr/pgsql-9.6/bin/pg_rewind --target-pgdata /var/lib/pgsql/9.6/data/ --source-server='host=10.1.88.46 port=5432 user=postgres dbname=postgres password=postgres' -P
connected to server
servers diverged at WAL position 0/B8003138 on timeline 2
rewinding from last common checkpoint at 0/B8002118 on timeline 2
reading source file list
reading target file list
reading WAL in target
need to copy 77 MB (total source directory size is 10139 MB)
79071/79071 kB (100%) copied
creating backup label and updating control file
syncing target data directory
Done!

pg_rewind 成功

修改recovery.conf 文件 启动数据库
$pg_ctl start -D $PGDATA

验证数据

postgres=# select count(1) from test_2;
count
-------
10000
(1 row)

原文地址:https://www.cnblogs.com/zhangeamon/p/7602269.html