PostgreSQL 流复制

文章目录

      • 1.流复制介绍
      • 2.异步流复制
        • 2.1.主库部署
        • 2.2.备库部署
        • 2.3.测试
      • 3.同步复制
        • 3.1.主库部署
        • 3.2.备库部署
        • 3.3.测试
      • 4.主备切换

  • 开源中间件
# PostgreSQLhttps://iothub.org.cn/docs/middleware/
https://iothub.org.cn/docs/middleware/postgresql/postgres-stream/

1.流复制介绍

流复制其原理为:备库不断的从主库同步相应的数据,并在备库apply每个WAL record,这里的流复制每次传输单位是WAL日志的record。

PostgreSQL物理流复制按照同步方式分为两类:

  • 异步流复制
  • 同步流复制

物理流复制具有以下特点:

  1. 延迟极低,不怕大事务
  2. 支持断点续传
  3. 支持多副本
  4. 配置简单
  5. 备库与主库物理完全一致,并支持只读

在这里插入图片描述

2.异步流复制

2.1.主库部署
  • 安装postgresql
# yum install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-7-x86_64/pgdg-redhat-repo-latest.noarch.rpm# yum install -y postgresql11-server # 关闭防火墙
firewall-cmd --state                 #查看默认防火墙状态(关闭后显示notrunning,开启后显示running)
systemctl stop firewalld.service     #停止firewall
systemctl start firewalld.service    #开启防火墙
systemctl disable firewalld.service  #禁止firewall开机启动
systemctl enable firewalld.service   #开启firewall开机启动
  • 初始化数据库
主库初始化
# /usr/pgsql-11/bin/postgresql-11-setup initdb启动服务 
# systemctl start postgresql-11 服务自启动
# systemctl enable postgresql-11切换用户,设置数据库密码 
# su - postgres
$ psql
# ALTER USER postgres with encrypted password 'postgres';
创建用于主从同步的用户, 用户名replica, 密码replica:
# CREATE ROLE replica login replication encrypted password 'replica';postgres=# \q
#-bash-4.2$ exit
  • 修改配置文件
1.修改连接权限
# vim /var/lib/pgsql/11/data/pg_hba.conf# 客户端访问
host    all             all             all                     md5
# replica是用来做备份的用户,172.51.216.82/32是备的IP地址
host    replication     replica         172.51.216.82/32        md5# 完整配置
# TYPE  DATABASE        USER            ADDRESS                 METHOD# "local" is for Unix domain socket connections only
local   all             all                                     peer
# IPv4 local connections:
host    all             all             127.0.0.1/32            ident
# IPv6 local connections:
host    all             all             ::1/128                 ident
# Allow replication connections from localhost, by a user with the
# replication privilege.
local   replication     all                                     peer
host    replication     all             127.0.0.1/32            ident
host    replication     all             ::1/128                 identhost    all             all             all                     md5
host    replication     replica         172.51.216.82/32        md52.修改数据库配置:
# vim /var/lib/pgsql/11/data/postgresql.conf同步增加配置:
synchronous_commit = on         # synchronization level;
synchronous_standby_names = 'msa'listen_addresses = '*'            # what IP address(es) to listen on;
port = 5432                # (change requires restart)
max_connections = 512            # (change requires restart)
shared_buffers = 128MB            # min 128kB
dynamic_shared_memory_type = posix    # the default is the first option
wal_level = hot_standby        # minimal, replica, or logical
archive_mode = on        # enables archiving; off, on, or always
archive_command = 'cp %p /var/lib/pgsql/11/data/pg_archive/%f'        # command to use to archive a logfile segment
max_wal_senders = 6        # max number of walsender processes
wal_keep_segments = 256    # in logfile segments, 16MB each; 0 disables
wal_sender_timeout = 60s    # in milliseconds; 0 disables
log_directory = 'log'    # directory where log files are written 修改完,要创建刚刚配置的一些目录结构:
# mkdir /var/lib/pgsql/11/data/pg_archive/
# chown -R postgres.postgres /var/lib/pgsql/11/data
  • 重启主库服务
# systemctl restart postgresql-11
# systemctl status postgresql-11 
2.2.备库部署
  • 安装postgresql
# yum install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-7-x86_64/pgdg-redhat-repo-latest.noarch.rpm# yum install -y postgresql11-server # 关闭防火墙
firewall-cmd --state                 #查看默认防火墙状态(关闭后显示notrunning,开启后显示running)
systemctl stop firewalld.service     #停止firewall
systemctl start firewalld.service    #开启防火墙
systemctl disable firewalld.service  #禁止firewall开机启动
systemctl enable firewalld.service   #开启firewall开机启动
  • 初始化数据库
主库初始化
# /usr/pgsql-11/bin/postgresql-11-setup initdb启动服务 
# systemctl start postgresql-11 服务自启动
# systemctl enable postgresql-11
  • 拷贝主库数据
1.进入data目录,清空从节点数据
# su - postgres
$ cd /var/lib/pgsql/11/data/
$ rm -rf *2.把主节点所有的数据文件都会拷贝过来
-bash-4.2$ pg_basebackup -h 172.51.216.81 -U replica -D /var/lib/pgsql/11/data/ -X stream -P
Password: replica 
  • 修改配置文件
1、修改从库配置文件
-bash-4.2$ vim /var/lib/pgsql/11/data/postgresql.conf listen_addresses = '*'            # what IP address(es) to listen on;
port = 5432                # (change requires restart)
max_connections = 1000            # (change requires restart)
shared_buffers = 128MB            # min 128kB
dynamic_shared_memory_type = posix    # the default is the first option
wal_level = replica        # minimal, replica, or logical
archive_mode = on        # enables archiving; off, on, or always
archive_command = 'cp %p /var/lib/pgsql/11/data/pg_archive/%f'        # command to use to archive a logfile segment
wal_sender_timeout = 60s    # in milliseconds; 0 disables
hot_standby = on            # "on" allows queries during recovery
max_standby_streaming_delay = 30s    # max delay before canceling queries
wal_receiver_status_interval = 10s    # send replies at least this often
hot_standby_feedback = on        # send info from standby to prevent
log_directory = 'log'    # directory where log files are written,2.创建恢复文件recovery.conf
-bash-4.2$ cp /usr/pgsql-11/share/recovery.conf.sample /var/lib/pgsql/11/data/recovery.conf
-bash-4.2$ vim /var/lib/pgsql/11/data/recovery.conf# 修改参数:
recovery_target_timeline = 'latest'   #同步到最新数据
standby_mode = on                     #指明从库身份
trigger_file = 'failover.now'
primary_conninfo = 'host=172.51.216.81 port=5432 user=replica password=replica'  #连接到主库信息 切换到root用户
$ exit
  • 重启从库服务
# systemctl restart postgresql-11
# systemctl start postgresql-11
# systemctl status postgresql-11# netstat -lntp
# netstat -nat
2.3.测试
进入主节点:
su - postgres
psql在主库上运行以下命令
postgres=# select client_addr,sync_state from pg_stat_replication;postgres=# select client_addr,sync_state from pg_stat_replication;client_addr  | sync_state 
---------------+------------172.51.216.82 | async
(1 row)postgres=# \x
Expanded display is on.
postgres=# select * from pg_stat_replication;
-[ RECORD 1 ]----+------------------------------
pid              | 8437
usesysid         | 16384
usename          | replica
application_name | walreceiver
client_addr      | 172.51.216.82
client_hostname  | 
client_port      | 37542
backend_start    | 2021-03-12 13:28:55.818239+08
backend_xmin     | 572
state            | streaming
sent_lsn         | 0/C01DE30
write_lsn        | 0/C01DE30
flush_lsn        | 0/C01DE30
replay_lsn       | 0/C01DE30
write_lag        | 
flush_lag        | 
replay_lag       | 
sync_priority    | 0
sync_state       | async# 方法-1
在主库端检查,说明89服务器是从节点,在接收流,而且是异步流复制:
postgres=# select usename , application_name , client_addr,sync_state from pg_stat_replication;
-[ RECORD 1 ]----+--------------
usename          | replica
application_name | walreceiver
client_addr      | 172.51.216.89
sync_state       | async# 方法-2
在主、从节点分别执行如下命令:# 主
postgres  34833  11712  0 14:14 ?        00:00:00 postgres: walsender replica 172.51.216.89(51848) streaming 0/9024250# 从
postgres  77147  77128  0 14:14 ?        00:00:03 postgres: walreceiver   streaming 0/9024250

3.同步复制

3.1.主库部署
  • 安装postgresql
# yum install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-7-x86_64/pgdg-redhat-repo-latest.noarch.rpm# yum install -y postgresql11-server # 关闭防火墙
firewall-cmd --state                 #查看默认防火墙状态(关闭后显示notrunning,开启后显示running)
systemctl stop firewalld.service     #停止firewall
systemctl start firewalld.service    #开启防火墙
systemctl disable firewalld.service  #禁止firewall开机启动
systemctl enable firewalld.service   #开启firewall开机启动
  • 初始化数据库
主库初始化
# /usr/pgsql-11/bin/postgresql-11-setup initdb启动服务 
# systemctl start postgresql-11 服务自启动
# systemctl enable postgresql-11切换用户,设置数据库密码 
# su - postgres
$ psql
# ALTER USER postgres with encrypted password 'postgres';
创建用于主从同步的用户, 用户名replica, 密码replica:
# CREATE ROLE replica login replication encrypted password 'replica';postgres=# \q
#-bash-4.2$ exit
  • 修改配置文件
1.修改连接权限
# vim /var/lib/pgsql/11/data/pg_hba.conf# 客户端访问
host    all             all             all                     md5
# replica是用来做备份的用户,172.51.216.82/32是备的IP地址
host    replication     replica         172.51.216.82/32        md5#完成配置
# TYPE  DATABASE        USER            ADDRESS                 METHOD# "local" is for Unix domain socket connections only
local   all             all                                     peer
# IPv4 local connections:
host    all             all             127.0.0.1/32            ident
# IPv6 local connections:
host    all             all             ::1/128                 ident
# Allow replication connections from localhost, by a user with the
# replication privilege.
local   replication     all                                     peer
host    replication     all             127.0.0.1/32            ident
host    replication     all             ::1/128                 identhost    all             all             all                     md5
host    replication     replica         172.51.216.82/32        md52.修改数据库配置:
# vim /var/lib/pgsql/11/data/postgresql.conf同步增加配置:
synchronous_commit = on         # synchronization level;
synchronous_standby_names = 'msa'listen_addresses = '*'            # what IP address(es) to listen on;
port = 5432                # (change requires restart)
max_connections = 512            # (change requires restart)
shared_buffers = 128MB            # min 128kB
dynamic_shared_memory_type = posix    # the default is the first option
wal_level = hot_standby        # minimal, replica, or logical
archive_mode = on        # enables archiving; off, on, or always
archive_command = 'cp %p /var/lib/pgsql/11/data/pg_archive/%f'        # command to use to archive a logfile segment
max_wal_senders = 6        # max number of walsender processes
wal_keep_segments = 256    # in logfile segments, 16MB each; 0 disables
wal_sender_timeout = 60s    # in milliseconds; 0 disables
log_directory = 'log'    # directory where log files are written 修改完,要创建刚刚配置的一些目录结构:
# mkdir /var/lib/pgsql/11/data/pg_archive/
# chown -R postgres.postgres /var/lib/pgsql/11/data
  • 重启主库服务
# systemctl restart postgresql-11
# systemctl status postgresql-11 
3.2.备库部署
  • 安装postgresql
# yum install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-7-x86_64/pgdg-redhat-repo-latest.noarch.rpm# yum install -y postgresql11-server # 关闭防火墙
firewall-cmd --state                 #查看默认防火墙状态(关闭后显示notrunning,开启后显示running)
systemctl stop firewalld.service     #停止firewall
systemctl start firewalld.service    #开启防火墙
systemctl disable firewalld.service  #禁止firewall开机启动
systemctl enable firewalld.service   #开启firewall开机启动
  • 初始化数据库
主库初始化
# /usr/pgsql-11/bin/postgresql-11-setup initdb启动服务 
# systemctl start postgresql-11 服务自启动
# systemctl enable postgresql-11
  • 拷贝主库数据
1.进入data目录,清空从节点数据
# su - postgres
$ cd /var/lib/pgsql/11/data/
$ rm -rf *2.把主节点所有的数据文件都会拷贝过来
-bash-4.2$ pg_basebackup -h 172.51.216.81 -U replica -D /var/lib/pgsql/11/data/ -X stream -P
Password: replica
  • 修改配置文件
1、修改从库配置文件
-bash-4.2$ vim /var/lib/pgsql/11/data/postgresql.conf listen_addresses = '*'            # what IP address(es) to listen on;
port = 5432                # (change requires restart)
max_connections = 1000            # (change requires restart)
shared_buffers = 128MB            # min 128kB
dynamic_shared_memory_type = posix    # the default is the first option
wal_level = replica        # minimal, replica, or logical
archive_mode = on        # enables archiving; off, on, or always
archive_command = 'cp %p /var/lib/pgsql/11/data/pg_archive/%f'        # command to use to archive a logfile segment
wal_sender_timeout = 60s    # in milliseconds; 0 disables
hot_standby = on            # "on" allows queries during recovery
max_standby_streaming_delay = 30s    # max delay before canceling queries
wal_receiver_status_interval = 10s    # send replies at least this often
hot_standby_feedback = on        # send info from standby to prevent
log_directory = 'log'    # directory where log files are written,2.创建恢复文件recovery.conf
-bash-4.2$ cp /usr/pgsql-11/share/recovery.conf.sample /var/lib/pgsql/11/data/recovery.conf
-bash-4.2$ vim /var/lib/pgsql/11/data/recovery.conf# 修改参数:
recovery_target_timeline = 'latest'   #同步到最新数据
standby_mode = on                     #指明从库身份
trigger_file = 'failover.now'
primary_conninfo = 'host=172.51.216.81 port=5432 user=replica password=replica application_name=msa'  #连接到主库信息 同步primary_conninfo增加:
application_name=msa切换到root用户
$ exit
  • 重启从库服务
# systemctl restart postgresql-11
# systemctl start postgresql-11
# systemctl status postgresql-11# netstat -lntp
# netstat -nat
3.3.测试
# 进入主节点:
su - postgres
psql在主库上运行以下命令
postgres=# select client_addr,sync_state from pg_stat_replication;postgres=# select client_addr,sync_state from pg_stat_replication;client_addr  | sync_state 
---------------+------------172.51.216.82 | sync
(1 row)postgres=# \x
Expanded display is on.
postgres=# select * from pg_stat_replication;
-[ RECORD 1 ]----+------------------------------
pid              | 61092
usesysid         | 16384
usename          | replica
application_name | msa
client_addr      | 172.51.216.82
client_hostname  | 
client_port      | 48152
backend_start    | 2021-03-12 14:30:54.523831+08
backend_xmin     | 573
state            | streaming
sent_lsn         | 0/100000D0
write_lsn        | 0/100000D0
flush_lsn        | 0/100000D0
replay_lsn       | 0/100000D0
write_lag        | 
flush_lag        | 
replay_lag       | 
sync_priority    | 1
sync_state       | sync# 方法-1
在主库端检查,说明89服务器是从节点,在接收流,而且是异步流复制:
postgres=# select usename , application_name , client_addr,sync_state from pg_stat_replication;
-[ RECORD 1 ]----+--------------
usename          | replica
application_name | walreceiver
client_addr      | 172.51.216.89
sync_state       | sync# 方法-2
在主、从节点分别执行如下命令:# 主
postgres  34833  11712  0 14:14 ?        00:00:00 postgres: walsender replica 172.51.216.89(51848) streaming 0/9024250# 从
postgres  77147  77128  0 14:14 ?        00:00:03 postgres: walreceiver   streaming 0/9024250

4.主备切换

  • 关闭主库
在主库执行 pg_ctl stop 模拟主库宕机。 
pg_ctl stop-bash-4.2$  pg_ctl stop
waiting for server to shut down.... done
server stopped这时备库日志会报错,提示 primary 主库连接不上
2021-03-15 13:22:57.311 CST [66145] FATAL:  could not connect to the primary server: could not connect to server: Connection refusedIs the server running on host "172.51.216.81" and acceptingTCP/IP connections on port 5432?
  • 激活备库
在备库执行 pg_ctl promote 激活备库 -bash-4.2$ pg_ctl promote
waiting for server to promote.... done
server promoted备库激活后可以插入数据,变为可读写。这时配置文件 recovery.conf 变为 recovery.done。 postgres=#  SELECT pg_is_in_recovery();pg_is_in_recovery 
-------------------f
(1 row)
  • 开源中间件
# PostgreSQLhttps://iothub.org.cn/docs/middleware/
https://iothub.org.cn/docs/middleware/postgresql/postgres-stream/

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/732744.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Linux运维_Bash脚本_编译安装Mesa-23.3.6(OpenGL)

Linux运维_Bash脚本_编译安装Mesa-23.3.6(OpenGL) Bash (Bourne Again Shell) 是一个解释器,负责处理 Unix 系统命令行上的命令。它是由 Brian Fox 编写的免费软件,并于 1989 年发布的免费软件,作为 Sh (Bourne Shell) 的替代品。 您可以在…

为什么main方法在Java中代表主线程?

main 方法在 Java 等编程语言中确实代表着程序的入口点,也就是程序开始执行的地方。当我们启动一个 Java 应用程序时,JVM(Java 虚拟机)会首先查找 main 方法,并从那里开始执行程序。 关于为什么 main 方法代表主线程&a…

unity学习(53)——选择角色界面--分配服务器返回的信息

好久没写客户端了,一上手还不太适应 1.经过测试,成功登陆后,客户端请求list_request,成功返回,如下图: 可见此时model第三个位置的参数是1.也成功返回了所有已注册角色的信息。 2.之前已知创建的角色信息…

141 Linux 系统编程18 ,线程,线程实现原理,ps –Lf 进程 查看

一 线程概念 什么是线程 LWP:light weight process 轻量级的进程,本质仍是进程(在Linux环境下) 进程:独立地址空间,拥有PCB 线程:有独立的PCB,但没有独立的地址空间(共享) 区别:在于是否共…

html前端的几种加密/解密方式

HTML前端的加密解密方式有以下几种: 一、base64加密 Base64编码:Base64是一种将二进制数据转换为可打印字符的编码方式。在前端,可以使用JavaScript的btoa()函数进行Base64编码,使用atob()函数进行解码。 var str "hello…

uniapp发行H5获取当前页面query

阅读uni的文档大致可得通过 onLoad与 onShow()的形参都能获取页面传递的参数,例如在开发时鼠标移动到方法上可以看到此方法的简短介绍 实际这里说的是打开当前页面的参数,在小程序端的时候测试并无问题,但是发行到H5时首页加载会造成参数获取…

掌握mysql,看完这篇文章就够了

1.mysql 学习数据库就是学习数据库管理系统(一个数据管理系统可以管理多个数据库) 安装 安装版本:mysql -installter -community-5.7.41.0.msl 流程 1.custom自定义安装 2.选择安装MySQl Server 5.7.41 - x64 3.默…

c++ 常用新特性总结【c++11】,【c++14】,【c++17】,【c++20】

文章目录 常用的c11新特性1.自动推导类型(auto)2.lambda表达式3.智能指针4.范围for循环5.右值引用 - 移动语义6.类型别名7.constexpr8.static_assert(静态断言)9.nullptr10.列表初始化11.继承构造函数12.显示虚函数重载(override)13.final14.变长模板参数15.新的容器与算法16.强…

代码随想录算法训练营第四十八天|583. 两个字符串的删除操作,72. 编辑距离

系列文章目录 代码随想录算法训练营第一天|数组理论基础,704. 二分查找,27. 移除元素 代码随想录算法训练营第二天|977.有序数组的平方 ,209.长度最小的子数组 ,59.螺旋矩阵II 代码随想录算法训练营第三天|链表理论基础&#xff…

第三方神秘顾客调查:如何选择专业的营业厅神秘顾客公司

选择专业的营业厅神秘顾客公司时,确实需要考虑多个因素,以确保您合作的公司能够为您提供高质量的服务和有价值的反馈。以下是选择营业厅神秘顾客公司时应考虑的关键因素: 1、公司声誉与经验:选择在行业内有良好声誉和丰富经验的神…

内容管理平台原来这么好用,优秀企业必备

内容管理平台是企业的强有力支持者,它可以使企业对旗下的各种网站、应用和其他数字内容进行集中管理,有效提高工作效率。对于企业的运营、市场推广和客户服务等各方面都有着重要的影响。今天,我们就来推荐三款值得尝试的内容管理平台。 首先…

论文的引用书写方法

前置操作 1、全选文献 2、在开始选项卡 段落功能区 选择编号功能 3、设置编号格式 [1] 论文的引用 1、光标放在需要引用论文的地方 2、选择引用选项卡 点击交叉引用 3、引用类型为编号项 引用内容为段落编号 选择需要的第几条参考文献

备战蓝桥杯---动态规划的一些思想2

话不多说,直接看题: 1.换根DP: 我们肯定不能对每一个根节点暴力求,我们不妨先求f[1],我们发现当他的儿子作为根节点时深度和为f[1](n-cnt[i])-cnt[i](cnt[i]表示以i为根的节点数),这样子两遍DFS…

论文阅读:Diffusion Model-Based Image Editing: A Survey

Diffusion Model-Based Image Editing: A Survey 论文链接 GitHub仓库 摘要 这篇文章是一篇基于扩散模型(Diffusion Model)的图片编辑(image editing)方法综述。作者从多个方面对当前的方法进行分类和分析,包括学习…

Python exec 函数解析:探索动态代码执行的无限可能!

在 Python 中,exec() 是一个内置函数,用于执行储存在字符串或文件中的 Python 代码。这个函数的灵活性使得它在某些情况下成为一种有用的工具,但也因为其潜在的安全风险而需要谨慎使用。本文将深入探讨 exec() 函数的使用方法、注意事项以及适…

P10095 [ROIR 2023 Day 1] 斐波那契乘积

难度:普及/提高- 题目背景 翻译自 ROIR 2023 D1T2。 斐波那契数指斐波那契数列(f0​1,f1​1,fi​fi−2​fi−1​)中出现的数。 题目描述 给定一个自然数 n,求出将其表示为大于 1 的斐波那契数的乘积的方式数量。 输入格式 …

微信小程序-可以用区域

简介 movable-view和movable-area是可移动的视图容器,在页面中可以拖拽滑动。 本篇文章将会通过该容器实现一个常用的拖拽按钮功能。 使用效果 代码实现 side-view.wtml 布局见下面代码,left view为内容区域,right view为操作按钮&a…

【初中up主分享】自己动手,丰衣足食!看我打造的下载利器!

代码如下: import os.path import tkinter as tk import tkinter.ttk as ttk import tkinter.filedialog as tf import pytube from urllib.error import URLError import tkinter.messagebox as tm import requests import io from PIL import ImageTk, Image imp…

软件测试自学和报班学习的区别,各有各的优势和缺点,大家看完之后自己选择喔

时代在进步,人们汲取知识的方式不再是单一的在书本上面,现在网络发达,只需要上网就能找到相关的好多知识,慢慢的大家越来越觉得有了这些知识,只要自己有自制力就完全能够自学到一定的程度。 在自学氛围的影响下&#…

【Python】科研代码学习:五 Data Collator,Datasets

【Python】科研代码学习:五 Data Collator,Datasets Data CollatorDefault data collatorDefaultDataCollatorDataCollatorWithPaddingPadding 其他 Data Collator Datasetsload_dataset其他一些基本操作 Data Collator HF官网API:Data Coll…