www.colben.cn/content/post/postgresql-replication.md
2021-11-14 14:32:08 +08:00

70 lines
2.0 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: "Postgresql 主从"
date: 2019-11-04T02:09:29+08:00
lastmod: 2019-11-04T02:09:29+08:00
tags: ["postgresql", "replcation", "同步"]
categories: ["database"]
---
# 主库配置
- 修改 postgresql.conf
```
listen_address = '*'
wal_level = replica
wax_wal_senders = 10
wal_keep_segments = 64
hot_standby = on
```
- 启动主库 postgresql-10 服务
```bash
systemctl start postgresql-10
```
- 创建同步账户
```sql
create user replica superuser password '123456';
-- 这里可以只赋予 replication 权限,后面从库复制初始数据库时使用其他有权限帐号
```
- 修改 pg_hba.conf
```
host replication replica samenet md5
```
# 从库配置
- 停止从库 postgresql-10 服务,清空数据库目录
```bash
systemctl stop postgresql-10
rm -rf /var/lib/pgsql/10/data/*
```
- 从主库复制初始数据库
```bash
pg_basebackup \
-h <主库ip> \
-U replica \
-F p \
-X stream \
-P -R \
-D /var/lib/pgsql/10/data/ \
-l backup_20191104
```
- -h 指定连接的数据库的主机名或IP地址
- -U 指定连接的用户名
- -F 指定了输出的格式支持p原样输出或者ttar格式输出
- -X 表示备份开始后启动另一个流复制连接从主库接收WAL日志
- -P 表示允许在备份过程中实时的打印备份的进度
- -R 表示会在备份结束后自动生成recovery.conf文件
- -D 指定备份写入的数据目录,需要与数据库配置的数据库目录一致,初次备份之前从库的数据目录需要手动清空
- -l 表示指定一个备份的标识
# 检查状态
- 检查从库进程
```bash
ps -ef|grep postgres
# 可以看到 wal sender 和 receiver process 两个进程
```
- 从库为只读模式,无法进行 增/删/改 操作
- 主库查看 replication 客户端
```sql
select client_addr,sync_state from pg_stat_replication;
```