环境信息
主机名 |
IP地址 |
操作系统 |
数据库版本 |
角色 |
master |
192.168.91.145 |
Euler 22.10 LTS |
PostgreSQL 17.5 |
主库 |
slave |
192.168.91.146 |
Euler 22.10 LTS |
PostgreSQL 17.5 |
从库 |
主库配置
编辑配置文件/data/postgresql-17.4/data/postgresql.conf
cat >> /data/postgresql-17.4/data/postgresql.conf <<EOF # 主库配置 wal_level = replica # 启用WAL日志 max_wal_senders = 10 # 最大流复制连接数 synchronous_commit = remote_apply # 同步提交模式(强一致性) wal_keep_size = 1024 # 保留的WAL日志大小(MB) EOF
|
编辑pg_hba.conf
文件,允许从库连接主库
cat >> /data/postgresql-17.4/data/pg_hba.conf <<EOF # pg_hba.conf文件,允许从库连接主库 host replication repl 192.168.91.145/32 trust host replication repl 192.168.91.146/32 trust EOF
|
创建repl用户
psql -h 127.0.0.1 -U postgres -c "CREATE ROLE repl WITH REPLICATION LOGIN PASSWORD '123456';" psql -h 127.0.0.1 -U postgres -c "SELECT * FROM pg_create_physical_replication_slot('slot_standby1');"
|
重启主库
systemctl restart postgresql
|
从库配置
停止从库服务
systemctl stop postgresql
|
删除data目录
mv /data/postgresql-17.4/data /data/postgresql-17.4/data_bak
|
从主库同步数据
su - postgres pg_basebackup -h 192.168.91.145 -U repl -D /data/postgresql-17.4/data/ -X stream -P -R
|
编辑配置文件/data/postgresql-17.4/data/postgresql.conf
cat >> /data/postgresql-17.4/data/postgresql.conf <<EOF # 从库配置 hot_standby = on # 允许只读查询 primary_conninfo = 'host=192.168.91.145 user=repl password=123456 application_name=standby1' primary_slot_name = 'slot_standby1' # 与主库复制槽一致 EOF
|
启动从数据库
systemctl start postgresql
|
主从验证
主库查看主从状态
psql -h 127.0.0.1 -U postgres -c "SELECT client_addr, state, sync_state FROM pg_stat_replication;"
|
client_addr | state | sync_state
172.22.16.112 | streaming | async (1 row)
|
主库创建数据库插入数据
CREATE TABLE test(id SERIAL PRIMARY KEY); INSERT INTO test VALUES (1);
|
从库查看数据