1.创建复制用户:
CREATE USER repl WITH replication login password 'repl';
2.编辑recovery文件:
cat /pgdata/10/data/recovery.conf
sync:
standby_mode = 'on'
primary_conninfo = 'host=192.168.56.202 port=5432 user=postgres application_name=db3 user=repl password=repl keepalives_idle=60 keepalives_interval=5 keepalives_count=5'
restore_command = ''
recovery_target_timeline = 'latest'
主库的配置文件postgresql.conf添加如下内容:
synchronous_standby_names = 'db3'
pg_ctl reload
async:
recovery_target_timeline = 'latest'
standby_mode = on
restore_command = ''
primary_conninfo = 'host=192.168.56.202 port=5432 user=repl password=repl'
3.在db3上执行,ip:192.168.56.203:
pg_basebackup -D /pgdata/10/data -Fp -Xs -v -P -h 192.168.56.202 -p 5432 -U repl
pg_basebackup: initiating base backup, waiting for checkpoint to complete ##如果在这一步出现夯住不动,可以在主库上手动执行checkpoint; 命令。
pg_basebackup: checkpoint completed
transaction log start point: 460B/6F006F68 on timeline 16
pg_basebackup: starting background WAL receiver
4.启动数据库:
pg_ctl start
5.检查主备库角色:
a.主库检查复制状态:
select * from pg_stat_replication;
备库:
ps -ef |grep postgres |grep receiver
主库:
ps -ef |grep postgres |grep sender
b.SELECT pg_is_in_recovery();
如果返回t说明是备库,返回f说明是主库。
c.查看数据库控制信息:
pg_controldata |grep cluster
主:Database cluster state: in production
备:Database cluster state: in archive recovery
d.查询pg_stat_replication视图:
主库上面有记录,备库无记录;
备注:
如果使用pha4pgsql,检查登录分布式事务,保证无密码可以登录:
psql -U postgres -h 10.11.55.31 -p 5432 -d postgres
6.postgresql主备切换步骤:
a.关闭主库,建议使用-m fast模式关闭:
pg_ctl stop -m fast
b.在备库上执行pg_ctl promote 命令激活备库,如果recovery.conf 变成recovery.done表示备库已切换成为主库:
pg_ctl promote
c.将老的主库切换成备库,在老的主库的$PGDATA目录下创建recovery.conf 文件( 如果此目录下不存在recovery.conf文件,
可以根据$PGHOME/recovery.conf.sample 模板文件复制一个,如果此目录下存在recovery.done 文件,需将recovery.done 文件
重命名为recovery.conf) ,配置和老的从库一样,只是primary conninfo 参数中的IP换成对端IP 。
cat recovery.conf
recovery_target_timeline = 'latest'
standby_mode = on
restore_command = ''
primary_conninfo = 'host=192.168.56.203 port=5432 user=repl password=repl'
d.启动老的主库,这时观察主、备进程是否正常,如果正常表示主备切换成功。
7.查询备库接受的lsn和日志名字相关信息:
9.x:
备库查询接受的日志lsn:
SELECT pg_last_xlog_receive_location();
select pg_last_xlog_replay_location();
通过函数pg_xlogfile_name确定具体的日志:
select pg_xlogfile_name(pg_last_xlog_replay_location());
两个WAL日志位置的偏移量:
SELECT pg_xlog_location_diff('4741/620E4CC8','4741/620E4CC9') ;
显示日志最近应用的时间:
SELECT pg_last_xact_replay_timestamp();
10.x:
在备库执行:
SELECT pg_last_wal_receive_lsn();
SELECT pg_last_wal_replay_lsn();
在主库根据备库查出的lsn查出具体的日志:
select pg_walfile_name('xxxxxx');
两个WAL日志位置的偏移量:
SELECT pg_wal_lsn_diff('4741/5B7C9488','4741/5D744000') ;
显示日志最近应用的时间:
SELECT pg_last_xact_replay_timestamp();