暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Pg主从机制

程序员的自留地 2021-04-20
1404

主从的两种模式

wal archiving,warm standby

这种模式是主库将已写满的wal log进行归档,从库通过读取归档的wal log来追踪主库的变化达到主从同步。优点是主从差异间隔时间可控;不用单独配置一个复制用户,并且不占用主库wal_sender的进程数量。缺点是主从间隔较长,这种机制必须等待一个wal log写满且归档完毕后从库才能读到,xlog 产生到下一个 xlog 之间的数据不会及时反映在从库。配置也比较复杂

主库配置

  1. 修改postgrsql.conf文件,增加如下配置

    wal_level  = 'hot_standby|archive'      # determines how much information is written to the WAL
    wal_keep_segments = 150
    archive_mode = on
    archive_command = 'test ! -f mnt/server/archivedir/%f && cp %p mnt/server/archivedir/%f'
    archive_timeout = 300                   # force a logfile segment switch after this number of seconds; 0 disables


从库配置

  1. 在数据目录下添加一个recovery.conf文件,内容如下

    standby_mode = 'on'
    restore_command = 'cp path/to/archive/%f %p'
    archive_cleanup_command = 'pg_archivecleanup path/to/archive %r'



stream replication, hot standby

这种模式基于主从之间建立一个tcp连接,从库通过这个连接直接去主库上拉取所需的wal。优点是配置简单,实时性好,可以在每次主库数据变更后通过wal log获取。所以通常是我们线上从库的选择。也就是前文提到的hot standby模式。

主库的配置

  1. 建立这样一个从库只需要增加一个如下权限的用户

    CREATE ROLE replicator REPLICATION LOGIN PASSWORD 'xxxxx';


  2. 然后在hba文件里对用户开放访问对主库的访问权限

    host    replication     replicator             192.168.232.48/32            md5


  3. 最后在postgresql.conf文件中增加如下配置

    wal_level  = 'hot_standby'
    max_wal_senders = 5             # Set the maximum number of concurrent connections from the stand by servers
    wal_keep_segments = 150         # in logfile segments, 16MB each; 0 disables


从库配置

  1. 修改postgresql.conf中的如下配置

    hot_standby = 'on'


  2. 在PG_DATA目录下放置recovery.conf文件,文件内容如下

    standby_mode = 'on'
    primary_conninfo = 'hostaddr=masterip port=5432 user=replicator password=xxxxx application_name=XXX'
    recovery_target_timeline='latest'



文章转载自程序员的自留地,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论