实现MySQL高可用性:从原理到实践

目录

一、概述

1.什么是MySQL高可用

2.方案组成

3.优势

二、资源清单

三、案例实施

1.修改主机名

2.安装MySQL数据库(Master1、Master2)

3.配置mysql双主复制

4.安装haproxy(keepalived1、keepalived2)

5.安装keepalived(keepalived1、keepalived2)

6.测试故障转移


一、概述

1.什么是MySQL高可用

MySQL高可用是指通过冗余设计,确保数据库服务在单点故障、网络中断或硬件随换等异常情况下,仍能持续对外提供服务,同时保证数据一致性。其核心目标实现‘零停机、零数据丢失’的业务连续性

2.方案组成

  • MySQL主主复制:两台Mysql实例互为主从,双向同步数据,均支持同步数据,均支持读写操作,提供冗余和扩展能力
  • Keepalivend:通过VRRP协议管理虚拟IP(VIP),监控MySQL状态,故障时自动将VIP漂移至存活节点,确保服务地址不变
  • HAProxy:作为反向代理和负载均衡器,将流量分发至MySQL节点,支持监控检查,读写分离和故障节点自动删除

3.优势

  • 高可用性:Keeplived实现秒级故障切换,HAProxy健康检查确保流量路由到正常节点,避免单点故障
  • 读写扩展:主主架构支持双节点并发写入,提高写入性能;HAProxy可配置读写分离,利用备份节点分担读压力
  • 灵活扩展:可横向扩展HAProxy和MySQL节点,支持动态调整负载均衡策略(如权重、轮询)

二、资源清单

主机

操作系统

IP地址

应用

Master1

OpenEuler 24.03

192.168.16.142

Mysql8

Master2

OpenEuler 24.03

192.168.16.143

Mysql8

Keepalived1

OpenEuler 24.03

192.168.16.144

Keepalived、haproxy

Keepalived2

OpenEuler 24.03

192.168.16.145

Keepalived、haproxy

三、案例实施

1.修改主机名

hostnamectl set-hostname master1
hostnamectl set-hostname master2
hostnamectl set-hostname Keepalived1
hostnamectl set-hostname Keepalived2

2.安装MySQL数据库(Master1、Master2)

dnf install -y tartar zxf autoinstall-mysql.tar.gzcd autoinstall-mysql./start.shcd
source /etc/profile
mysql -uroot -p'临时密码'
ALTER USER 'root'@'localhost' IDENTIFIED BY '123456';
mysql -uroot -p123456

3.配置mysql双主复制

  • 二进制日志配置
    • Master1
      vi /etc/my.cnf[mysqld]
      log-bin=master1-bin    #启用二进制日志并指定其存储路径
      binlog_format = MIXED    #定义二进制日志的记录格式为混合模式
      server-id=1    #为mysql实例分配一个唯一的服务器标识符
    • Master2
      vi /etc/my.cnf[mysqld]
      log-bin=master2-bin    #启用二进制日志并指定其存储路径
      binlog_format = MIXED    #定义二进制日志的记录格式为混合模式
      server-id=2   #为mysql实例分配一个唯一的服务器标识符
  • 重启服务(Master1、Master2)
    systemctl restart mysqld
  • 登录mysql程序,给从服务器授权(Master1、Master2)
    mysql -uroot -p123456#创建用户
    CREATE USER 'myslave'@'%' IDENTIFIED BY '123456';
    #授权同步给所有用户
    GRANT REPLICATION SLAVE ON  *.* TO 'myslave'@'%';
    #修改密码
    ALTER USER 'myslave'@'%' IDENTIFIED WITH mysql_native_password BY '123456';
    #刷新配置
    FLUSH PRIVILEGES;
    #查看状态 
    show master status;
    #Master1
    +--------------------+----------+--------------+------------------+-------------------+
    | File               | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
    +--------------------+----------+--------------+------------------+-------------------+
    | master1-bin.000001 |     1147 |              |                  |                   |
    +--------------------+----------+--------------+------------------+-------------------+
    1 row in set (0.00 sec)#Master2
    +--------------------+----------+--------------+------------------+-------------------+
    | File               | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
    +--------------------+----------+--------------+------------------+-------------------+
    | master2-bin.000001 |     1150 |              |                  |                   |
    +--------------------+----------+--------------+------------------+-------------------+
    1 row in set (0.00 sec)
  • 登录mysql,配置同步
    • Master1
      mysql -uroot -p123456
      #连接主节点
      change master to master_host='192.168.16.143', master_user='myslave', master_password='123456',master_log_file='master2-bin.000001',master_log_pos=1150;
      #开启同步
      start slave;
      #查看状态
      show slave status\G#查看出来显示#            Slave_IO_Running: Yes#           Slave_SQL_Running: Yes
    • Master2
      mysql -uroot -p123456
      #连接主节点
      change master to master_host='192.168.16.142', master_user='myslave', master_password='123456',master_log_file='master1-bin.000001',master_log_pos=1147;
      #开启同步
      start slave;
      #查看状态
      show slave status\G#查看出来显示#            Slave_IO_Running: Yes#           Slave_SQL_Running: Yes

4.安装haproxy(keepalived1、keepalived2)

  • 安装haproxy
    dnf install  -y haproxy
  • 编辑haproxy配置文件
    vi /etc/haproxy/haproxy.cfg globallog         127.0.0.1 local2chroot      /var/lib/haproxypidfile     /var/run/haproxy.piduser        haproxygroup       haproxydaemonmaxconn     4000defaultsmode                    tcplog                     globaloption                  tcplogoption                  dontlognullretries                 3timeout http-request    5stimeout queue           1mtimeout connect         5stimeout client          1mtimeout server          1mtimeout http-keep-alive 5stimeout check           5smaxconn                 3000listen mysqlbind 0.0.0.0:3306          # 显式指定监听地址和端口balance leastconn           # 负载均衡算法server mysql1 192.168.16.142:3306 check port 3306 maxconn 300server mysql2 192.168.16.143:3306 check port 3306 maxconn 300#mode tcp:表示tcp代理
    #listen mysql 0.0.0.0:3306:创建一个名为mysql的监听服务
    #bind 0.0.0.0:3306:绑定到所有网卡的3306端口,作为流量入口
    #balance leastcnn:指定使用最少连接数分配在请求,将新连接导向当前活跃最少的后端服务器,避免单点过载
    #Server声明两个MySqL服务器节点mysql1和mysql2,分别指192.168.16.142:3306和192.168.16.143:3306
    #check prot 3306:通过检查节点的3306端口是否响应,判断存活状态
    #maxconn 300 :限制每个后端节点的最大并发连接数300
    
  • 检查配置文件并启动服务
    haproxy -c -f /etc/haproxy/haproxy.cfg 
    systemctl start haproxy
    systemctl enable haproxy
    ss -nlpt | grep 3306
  • 测试
    [root@master1 ~]# mysql -umyslave -p123456 -h192.168.16.144 -P3306
    mysql: [Warning] Using a password on the command line interface can be insecure.
    Welcome to the MySQL monitor.  Commands end with ; or \g.
    Your MySQL connection id is 16
    Server version: 8.0.36 MySQL Community Server - GPLCopyright (c) 2000, 2024, Oracle and/or its affiliates.Oracle is a registered trademark of Oracle Corporation and/or its
    affiliates. Other names may be trademarks of their respective
    owners.Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.mysql> exit

5.安装keepalived(keepalived1、keepalived2)

  • 安装keepalived
    dnf install -y keepalived
  • 编辑keepalived配置文件
    • keepalived1配置
      vi /etc/keepalived/keepalived.conf! Configuration File for keepalivedglobal_defs {router_id r1
      }vrrp_script chk_haproxy {script "/etc/keepalived/chk.sh"interval 2
      }vrrp_instance VI_1 {state BACKUPnopreemptinterface ens33virtual_router_id 51priority 100advert_int 1authentication {auth_type PASSauth_pass 1111}virtual_ipaddress {192.168.16.100}track_script {chk_haproxy}notify_backup "/etc/init.d/haproxy restart"notify_fault "/etc/init.d/haproxy stop"
      }
    • 添加监控脚本并启动keepailved
      vi /etc/keepalived/chk.sh
      #!/bin/bash
      #
      if [ $(ps -C haproxy --no-header | wc -l) -eq 0 ]; then/etc/init.d/keepalived stop
      fichmod +x /etc/keepalived/chk.sh 
      systemctl start keepalived
      systemctl enable keepalived
    • keepalived2配置
      vi /etc/keepalived/keepalived.conf! Configuration File for keepalivedglobal_defs {router_id r2
      }vrrp_script chk_haproxy {script "/etc/keepalived/chk.sh"interval 2
      }vrrp_instance VI_1 {state BACKUPnopreemptinterface ens33virtual_router_id 51priority 99advert_int 1authentication {auth_type PASSauth_pass 1111}virtual_ipaddress {192.168.16.100}track_script {chk_haproxy}notify_backup "/etc/init.d/haproxy restart"notify_fault "/etc/init.d/haproxy stop"
      }
    • 添加监控脚本并启动keepailved
      vi /etc/keepalived/chk.sh
      #!/bin/bash
      #
      if [ $(ps -C haproxy --no-header | wc -l) -eq 0 ]; then/etc/init.d/keepalived stop
      fichmod +x /etc/keepalived/chk.sh 
      systemctl start keepalived
      systemctl enable keepalived
  • keepalived1上查看VIP
    ip a#inet 192.168.16.100/32 scope global ens33#valid_lft forever preferred_lft forever
  • 使用VIP连接Mysql(Master1)
    [root@master1 ~]# mysql -umyslave -p123456 -P3306 -h192.168.16.100
    mysql: [Warning] Using a password on the command line interface can be insecure.
    Welcome to the MySQL monitor.  Commands end with ; or \g.
    Your MySQL connection id is 16
    Server version: 8.0.36 MySQL Community Server - GPLCopyright (c) 2000, 2024, Oracle and/or its affiliates.Oracle is a registered trademark of Oracle Corporation and/or its
    affiliates. Other names may be trademarks of their respective
    owners.Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.mysql> 

6.测试故障转移

  • 关闭master1主机,测试使用vip能否正常访问mysql数据库(Master2)
    ping 192.168.16.142[root@master1 ~]# mysql -umyslave -p123456 -P3306 -h192.168.16.100
    mysql: [Warning] Using a password on the command line interface can be insecure.
    Welcome to the MySQL monitor.  Commands end with ; or \g.
    Your MySQL connection id is 16
    Server version: 8.0.36 MySQL Community Server - GPLCopyright (c) 2000, 2024, Oracle and/or its affiliates.Oracle is a registered trademark of Oracle Corporation and/or its
    affiliates. Other names may be trademarks of their respective
    owners.Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.mysql> 
  • 关闭keeplived1,测试使用vip能否正常访问mysql数据库(Master2)
    ping 192.168.16.142[root@master1 ~]# mysql -umyslave -p123456 -P3306 -h192.168.16.100
    mysql: [Warning] Using a password on the command line interface can be insecure.
    Welcome to the MySQL monitor.  Commands end with ; or \g.
    Your MySQL connection id is 16
    Server version: 8.0.36 MySQL Community Server - GPLCopyright (c) 2000, 2024, Oracle and/or its affiliates.Oracle is a registered trademark of Oracle Corporation and/or its
    affiliates. Other names may be trademarks of their respective
    owners.Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.mysql> 

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

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

相关文章

CSS学习笔记8——表格

一、表格 1-1、创建表格 在Word文档中,如果要创建表格,只需插入表格,然后设定相应的行数和列数即可。然而在HTML网页中,所有的元素都是通过标签定义的,要想创建表格,就需要使用与表格相关的标签。使用标签…

爬虫学习笔记(一)

目的 通过编写程序爬取互联网上的优质资源 爬虫必须要使用python吗 非也~ 编程语言知识工具,抓取到数据才是目的,而大多数爬虫采用python语言编写的原因是python的语法比较简单,python写爬虫比较简单!好用!而且pyt…

大厂面试:MySQL篇

前言 本章内容来自B站黑马程序员java大厂面试题和小林coding 博主学习笔记,如果有不对的地方,海涵。 如果这篇文章对你有帮助,可以点点关注,点点赞,谢谢你! 1.MySQL优化 1.1 定位慢查询 定位 一个SQL…

C++_数据结构_详解红黑树

✨✨ 欢迎大家来到小伞的大讲堂✨✨ 🎈🎈养成好习惯,先赞后看哦~🎈🎈 所属专栏:C学习 小伞的主页:xiaosan_blog 制作不易!点个赞吧!!谢谢喵!&…

DNA复制过程3D动画教学工具

DNA复制过程3D动画教学工具 访问工具页面: DNA复制动画演示 工具介绍 我开发了一个交互式的DNA复制过程3D动画演示工具,用于分子生物学教学。这个工具直观展示了: DNA双螺旋结构的解旋过程碱基互补配对原理半保留复制机制完整的复制周期动画 主要特点…

使用阿里云 CDN 保护网站真实 IP:完整配置指南

使用阿里云 CDN 保护网站真实 IP:完整配置指南 一、宝塔面板准备工作1. 确认网站部署状态2. 宝塔中检查网站配置 二、配置阿里云 CDN1. 添加域名到 CDN2. 配置 DNS 解析3. 配置成功确认 三、宝塔面板安全加固(隐藏 IP 的关键步骤)1. 禁止通过…

PHP经验笔记

isset — 检测变量是否设置,并且不是NULL; 若变量存在且值不为NULL,则返回 TURE 若变量存在且其值为NULL或变量不存在,则返回 FALSE 结论 1. 当变量为空字符串、数值0和布尔值false时,isset全部返回true 2. 当变量不存在和变量存在且值为NULL…

Linux——安装NVM

1. 安装命令 官方地址:https://github.com/nvm-sh/nvm curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash2. 安装完成后执行命令 source ~/.bashrc3. 验证 nvm -v

CentOS 7 磁盘阵列搭建与管理全攻略

CentOS 7 磁盘阵列搭建与管理全攻略 在数据存储需求日益增长的今天,磁盘阵列(RAID)凭借其卓越的性能、数据安全性和可靠性,成为企业级服务器和数据中心的核心存储解决方案。CentOS 7 作为一款稳定且功能强大的 Linux 操作系统&am…

C++每日训练 Day 18:构建响应式表单与数据验证(初学者友好)

📘 本篇目标:在前几日协程与事件驱动机制基础上,构建一个响应式表单系统,实现用户输入的异步验证与反馈。通过协程挂起/恢复机制,简化异步逻辑,提升代码可读性。 🔁 回顾 Day 17:响应…

Vue初步总结-摘自 黑马程序员

本文摘自 bilibili 前端最新Vue2Vue3基础入门到实战项目全套教程,自学前端vue就选黑马程序员,一套全通关! 更多详情可参考: https://www.yuque.com/u26161316/pic6n4/heyv8nv8ubfk3fhe?singleDoc# 《Vue》

【基于Qt的QQ音乐播放器开发实战:从0到1打造全功能音乐播放应用】

🌹 作者: 云小逸 🤟 个人主页: 云小逸的主页 🤟 motto: 要敢于一个人默默的面对自己,强大自己才是核心。不要等到什么都没有了,才下定决心去做。种一颗树,最好的时间是十年前,其次就是现在&…

线程池(二):深入剖析synchronized关键字的底层原理

线程池(二):深入剖析synchronized关键字的底层原理 线程池(二):深入剖析synchronized关键字的底层原理一、基本使用1.1 修饰实例方法1.2 修饰静态方法1.3 修饰代码块 二、Monitor2.1 Monitor的概念2.2 Moni…

Linux CentOS 7 安装Apache 部署html页面

*、使用yum包管理器安装Apache。运行以下命令: sudo yum install httpd *、启动Apache服务 sudo systemctl start httpd *、设置Apache服务开机自启 # 启用开机自启动 sudo systemctl enable httpd# 禁用开机自启动 sudo systemctl disable httpd *、验证Apac…

前端设置三行文本省略号,失效为什么?

实际效果:第三行出现省略号,但是第四行依旧显示了部分文字 这个问题通常是由于 CSS 多行文本截断(-webkit-line-clamp)的计算方式或布局冲突导致的。以下是完整解决方案,确保三行文本截断正确显示省略号,并…

git学习之git常用命令

1. 初始化仓库 git init初始化一个新的 Git 仓库。 2. 克隆远程仓库 git clone <repository-url>从远程服务器克隆一个已有仓库到本地。 3. 配置用户名和邮箱 git config --global user.name "Your Name" git config --global user.email "youexampl…

【Spring Boot】深入解析:#{} 和 ${}

1.#{} 和 ${}的使用 1.1数据准备 1.1.1.MySQL数据准备 &#xff08;1&#xff09;创建数据库&#xff1a; CREATE DATABASE mybatis_study DEFAULT CHARACTER SET utf8mb4;&#xff08;2&#xff09;使用数据库 -- 使⽤数据数据 USE mybatis_study;&#xff08;3&#xff…

Poco C++全面开发指南:日期和时间

时间戳 时间戳是指格林威治时间1970年01月01日00时00分00秒&#xff08;北京时间1970年01月01日08时00分00秒&#xff09;起至现在的总秒数。在poco中可以可以使用Timestamp类获取。 #include <Poco/Timestamp.h> #include <iostream>int main() {Poco::Timestam…

水利三维可视化平台怎么做?快速上手的3步指南

分享大纲&#xff1a; 1、了解水利三维可视化平台 2、选择合适的开发平台 3、快速搭建水利三维可视化平台 第一步&#xff1a;了解水利三维可视化平台 水利三维可视化平台是利用大数据、物联网、数字孪生等技术&#xff0c;将物理实体数字化建模&#xff0c;并通过三维可视化技…

高级前端面试题:基于2025年最新技术体系

高级前端面试题:基于2025年最新技术体系 引言 随着前端技术的不断发展,2025年的前端面试题也呈现出新的特点和趋势。本报告基于最新的前端技术体系,收集了当前热门的面试题,旨在帮助准备高级前端工程师面试的候选人全面了解面试考察点。报告内容涵盖HTML5 Canvas、WebGL、…