2)操作系统版本:
[postgres@server2 data]$ cat /etc/redhat-release
Red Hat Enterprise Linux release 9.3 (Plow)
3)数据库版本:
postgres@[local]:5432/postgres-11653#=select version();
version
----------------------------------------------------------------------------------------------------------------
PostgreSQL 16.1 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 11.4.1 20230605 (Red Hat 11.4.1-2.1.0.1), 64-bit
(1 row)
2.创建主备流复制
2.1 在主备两台机器修改 /etc/hosts 文件
vim /etc/hosts
192.168.133.151 server1
192.168.133.152 server2
2.2 在主库设置
1)建立同步用户
postgres=# create role rep1 login replication encrypted password 'rep1';
[postgres@server2 pg_log]$ psql -h server2
Password for user postgres:
psql (16.1)
Type "help" for help.
postgres@server2:5432/postgres-11497#=\d
List of relations
Schema | Name | Type | Owner
--------+----------------+-------+----------
public | emp | table | postgres
public | pg_buffercache | view | postgres
(2 rows)
postgres@server2:5432/postgres-11497#=select * from emp;
emp
-----
100
(1 row)
通过以上可以看出,主库新增数据已经同步到备库
4.主备切换
4.1 停止主库
[postgres@server1 data]$ pg_ctl stop
waiting for server to shut down.... done
server stopped
[postgres@server1 data]$
[postgres@server1 data]$
[postgres@server1 data]$ pg_ctl status
pg_ctl: no server running
4.2 提升备库为主
pg_ctl promote
postgres@server2 pg_log]$ pg_ctl promote
waiting for server to promote.... done
server promoted
[postgres@server2 pg_log]$ pg_ctl status
pg_ctl: server is running (PID: 11345)
/u01/app/postgres/bin/postgres
[postgres@server2 pg_log]$ pg_controldata |grep stat
Database cluster state: in production
[postgres@server2 pg_log]$
4.5 启动新备库
[postgres@server1 data]$ pg_ctl restart
waiting for server to shut down.... done
server stopped
waiting for server to start....2023-12-17 22:53:08.352 CST [3340] LOG: redirecting log output to logging collector process
2023-12-17 22:53:08.352 CST [3340] HINT: Future log output will appear in directory "pg_log".
done
server started
4.6 验证
新备库
[postgres@server1 data]$ pg_controldata |grep state
Database cluster state: in archive recovery
新主库
[postgres@server2 data]$ pg_controldata |grep stat
Database cluster state: in production
[postgres@server2 data]$ psql
psql (16.1)
Type "help" for help.
postgres@[local]:5432/postgres-11653#=\x
Expanded display is on.
postgres@[local]:5432/postgres-11653#=select pid, usename,client_addr,state,sync_state,reply_time from pg_stat_replication;
-[ RECORD 1 ]------------------------------
pid | 11644
usename | rep1
client_addr | 192.168.133.151
state | streaming
sync_state | async
reply_time | 2023-12-17 22:55:48.476883+08