1 环境
主机:
ip: 192.168.2.169
系统:centos6.5 64bit
数据库版本:postgresql 10.4
数据库安装位置:/opt/pg10.4
从机:
ip: 192.168.2.190
系统:centos6.5 64bit
数据库版本:postgresql 10.4
数据库安装位置:/opt/pg10.4
2 主机设置
修改主机系统参数配置
启动数据库,打开psql。输入下面三条SQL设置参数。
psql (10.4)
Type "help" for help.
postgres=# alter system set wal_level = hot_standby ;
ALTER SYSTEM
postgres=# alter system set max_wal_senders = 3 ;
ALTER SYSTEM
postgres=# alter system set hot_standby = on ;
ALTER SYSTEM
postgres=#
修改pg_hba.conf中的流复制配置
在data目录下的pg_hba.conf文件末尾加上这句话,让从机能访问主机的监听端口。注意:需要关闭防火墙
host replication dba 192.168.2.0/16 md5
3 从机设置
初始化数据库–把主库中的历史数据导入
在数据库bin目录下输入命令
pg_basebackup -D /opt/pg10.4/data -Fp -Xs -v -P -h 192.168.2.169 -p 5432 -U postgres
这里就将主库中的data导过来了,/opt/pg10.4/data在执行这条命令前,应该不存在这个文件目录。
[peter@localhost bin]$ pg_basebackup -D /opt/pg10.4/data -Fp -Xs -v -P -h 192.168.2.169 -p 5432 -U postgres
Password:
pg_basebackup: initiating base backup, waiting for checkpoint to complete
pg_basebackup: checkpoint completed
pg_basebackup: write-ahead log start point: 0/8000028 on timeline 4
pg_basebackup: starting background WAL receiver
31472/31472 kB (100%), 1/1 tablespace
pg_basebackup: write-ahead log end point: 0/8000130
pg_basebackup: waiting for background process to finish streaming ...
pg_basebackup: base backup completed
[peter@localhost bin]$
在/opt/pg10.4/data目录下创建 recovery.conf文件增加如下设置
standby_mode = on #说明这台机器为从机
primary_conninfo = 'host=192.168.2.169 port=5432 user=postgres password=dba$123'
###4 重启数据库
主机、从机都重新启动数据库。
在主机上查询流复制信息
通过sql查询可以看到192.168.2.190也就是从机配置了复制流。
postgres=# select pid,usename,application_name,client_addr,state,client_port,sent_lsn,backend_start ,sync_state from pg_stat_replication;
pid | usename | application_name | client_addr | state | client_port |
sent_lsn | backend_start | sync_state
-------+----------+------------------+---------------+-----------+-------------+
-----------+-------------------------------+------------
14198 | postgres | walreceiver | 192.168.2.190 | streaming | 56858 |
0/A0001B0 | 2019-03-20 23:58:36.580964-07 | async
(1 row)
postgres=#
###5 复制流的数据测试
在主机上操作
postgres=# create table ttb_02(id int ,name char(12));
CREATE TABLE
postgres=# insert into ttb_02(id,name)values(1,'关羽');
INSERT 0 1
postgres=# insert into ttb_02(id,name)values(3,'张飞');
INSERT 0 1
postgres=# insert into ttb_02(id,name)values(4,'赵云');
INSERT 0 1
postgres=# select * from ttb_02;
id | name
----+----------------
1 | 关羽
3 | 张飞
4 | 赵云
(3 rows)
postgres=#
查询从机是否同步
postgres=# \dt
List of relations
Schema | Name | Type | Owner
--------+--------+-------+----------
public | test | table | postgres
public | ttb_02 | table | postgres
(2 rows)
postgres=# select * from ttb_02;
id | name
----+----------------
1 | 关羽
3 | 张飞
4 | 赵云
(3 rows)
postgres=#
从机不能做写操作
在从机上对数据增删查都是不允许的,会报错
postgres=# create table ttb_03(id int ,name char(12));
ERROR: cannot execute CREATE TABLE in a read-only transaction