pg_rewind增量同步备库

来源:互联网 发布:知乎 怎么忘记暗恋的人 编辑:程序博客网 时间:2024/06/06 08:27


/*
在数据库变得比较大时, 例如上TB, 如果部署了PostgreSQL primary-standby 流复制或者log shipping HA.
当发生了failover, old primary节点可能因为某些原因需要重新同步数据. 
在广域网上, 由于网络异常也可能造成standby节点落后主节点, 导致需要重新同步数据.
小数据库重新同步数据很方便, 全量或者使用rsync增量同步都可以. 
但是数据库很大的情况下, rsync也会变得非常慢, 而且大量消耗主机IO资源. 
PostgreSQL 社区有提议在核心中加入通过wal文件解析, 达到增量同步到目的
*/


--配置9.5版本的主从环境


--在pg的9.5版本中 checkpoint_segments参数已经被移除
--max_wal_size 换算大小 ,http://www.postgresql.org/docs/9.5/static/release-9-5.html
--max_wal_size = (3 * checkpoint_segments) * 16MB
max_wal_size = 1GB






--pg_rewind 前提条件
1. full_page_writes
2. wal_log_hints 设置成 on 或者 PG 在初始化时开启 checksums 功能




--查看从库的配置恢复文件
[postgres@rudy_01 5430]$ grep ^[a-z] recovery.conf 
standby_mode = on
recovery_target_timeline = 'latest'
primary_conninfo = 'host=rudy_01 port=5431 user=repuser'
trigger_file = '/usr/local/postgresql/9.5/5430/postgresql.trigger.5430'




--启动备库为主库
touch /usr/local/postgresql/9.5/5430/postgresql.trigger.5430
--在原来的备机点上插入测试数据
create table test_2(id int4);
insert into test_2(id) select n from generate_series(1,10000) n;




--在主机点上停止原主机点数据库
[postgres@rudy_01 5430]$  pg_controldata | grep cluster
Database cluster state:               in production
[postgres@rudy_01 5430]$ pg_ctl stop -m fast -D $PGDATA
waiting for server to shut down.....
server stopped
--备注:停完原主库后,千万不能立即以备节点形式拉起老库,否则在执行 pg_rewind 时会报,"target server must be shut down cleanly" 错误


-- 如果有如下错误
target server needs to use either data checksums or "wal_log_hints = on"
--备注:数据库在 initdb 时需要开启 checksums 或者设置  "wal_log_hints = on"




--注意要备份好原来主库的配置文件,因为pg_rewind会把配置文件也同步过来覆盖原来的配置文件
cp pg_hba.conf pg_hba.bak
cp postgresql.conf postgresql.bak


--在原主库上执行pg_rewind上操作
--千万注意,如要在原主库关闭之前,又对数据库进行了增删查改,它们会对覆盖
pg_rewind --target-pgdata $PGDATA --source-server='host=rudy_01 port=5430 user=postgres dbname=postgres password=123456' -P 


connected to server
servers diverged at WAL position 0/9DECBC0 on timeline 2
rewinding from last common checkpoint at 0/6000138 on timeline 2
reading source file list
reading target file list
reading WAL in target
need to copy 196 MB (total source directory size is 213 MB)
201117/201117 kB (100%) copied
creating backup label and updating control file
Done!




--在原来的主库上创建复制配置文件
cat recovery.conf 


standby_mode = on
recovery_target_timeline = 'latest'
primary_conninfo = 'host=rudy_01 port=5430 user=repuser'
trigger_file = '/usr/local/postgresql/9.5/5431/postgresql.trigger.5431'


--启动原主库做备库使用
pg_ctl start -D $PGDATA

0 0
原创粉丝点击