mysql

1.mysql的备份与恢复

数据备份的重要性

  • 在生产环境中,数据的安全性至关重要

  • 任何数据的丢失都可能产生严重的后果

  • 造成数据丢失的原因

    • 程序错误

    • 人为操作错误

    • 运算错误

    • 磁盘故障

    • 灾难(如火灾、地震)和盗窃

数据库备份的分类

从物理与逻辑的角度,备份可分为

  • 物理备份:对数据库操作系统的物理文件(如数据文件、日志文件等)的备份
    • 物理备份方法
      • 冷备份(脱机备份):是在关闭数据库的时候进行的
      • 热备份(联机备份):数据库处于运行状态,依赖于数据库的日志文件
      • 温备份:数据库锁定表格(不可写入但可读)的状态下进行备份操作
  • 逻辑备份:对数据库逻辑组件(如:表等数据库对象)的备份

常见的备份方法

  • 物理冷备
    • 备份时数据库处于关闭状态,直接打包数据库文件
    • 备份速度快,恢复时也是最简单的
  • 专用备份工具mydump或mysqlhotcopy
    • mysqldump常用的逻辑备份工具
    • mysqlhotcopy仅拥有备份MylSAM和ARCHIVE表
  • 启用二进制日志进行增量备份
    • 进行增量备份,需要刷新二进制日志
  • 第三方工具备份
    • 免费的MvSQL热备份软件PerconaXtraBackup

冷备份

# 备份(推荐写法)
[root@mysql01 ~]# systemctl stop mysqld                       # 先停止服务
[root@mysql01 ~]# cd /usr/local/mysql/data
[root@mysql01 data]# mkdir /mysql_bak
[root@mysql01 data]# tar czf /mysql_bak/mysql-backup-$(date +%F).tar.gz *
[root@mysql01 data]# systemctl start mysqld              # 备份完成后启动服务
#测试服务正常

# 删除数据
[root@mysql01 ~]# systemctl stop mysqld  # 先停止服务
[root@mysql01 ~]# rm -rf /usr/local/mysql/data/*            # 清空数据目录(谨慎操作!)
#再次开启测试,发现数据库坏了
[root@mysql01 ~]# systemctl start mysqld

#停止数据库,恢复数据库
[root@mysql01 ~]# systemctl stop mysqld
[root@mysql01 ~]# tar xzf /mysql_bak/mysql-backup-2025-10-15.tar.gz -C /usr/local/mysql/data/
[root@mysql01 ~]# chown -R mysql:mysql /usr/local/mysql/data       # 恢复权限
[root@mysql01 ~]# systemctl start mysqld          # 启动服务
#再次测试,发现数据库恢复了

逻辑备份

#备份数据库
[root@mysql01 ~]# systemctl start mysqld
[root@mysql01 ~]# mysqldump -u root -p school > /mysql_bak/school.sql
Enter password:
[root@mysql01 ~]# ls /mysql_bak/school.sql
mysql_bak/school.sql
[root@mysql01 ~]# cat /mysql_bak/school.sql

#备份多个数据库
[root@mysql01 ~]# mysqldump -u root -p --databases school mysql > /mysql_bak/school-mysql.sql
Enter password:
[root@mysql01 ~]# cat /mysql_bak/school-mysql.sql
#备份所有数据库
[root@mysql01 ~]# mysqldump -u root -p --opt --all-databases > /mysql_bak/all.sql
Enter password:
[root@mysql01 ~]# cat /mysql_bak/all.sql 
#备份整个表
[root@mysql01 ~]# mysqldump -u root -p school info  > /mysql_bak/info.sql
Enter password:
[root@mysql01 ~]# cat /mysql_bak/info.sql

恢复数据

[root@mysql01 ~]# mysql -u root -p
Enter password:

mysql> use school
mysql> show tables;
+------------------+
| Tables_in_school |
+------------------+
| info             |
+------------------+
1 row in set (0.00 sec)

mysql> drop table info;
Query OK, 0 rows affected (0.01 sec)

mysql> source /mysql_bak/info.sql

mysql> show tables;
+------------------+
| Tables_in_school |
+------------------+
| info             |
+------------------+
1 row in set (0.00 sec)

增量备份

[root@mysql01 ~]# vim /etc/my.cnf
------------------------
[mysqld]
log-bin=mysql-bin #这段下面最后加一行

[root@web-server ~]# systemctl restart mysqld.service

[root@mysql01 ~]# ls /usr/local/mysql/data/
auto.cnf    client-cert.pem  ibdata1      ibtmp1            mysql-bin.index     public_key.pem   server-key.pem
ca-key.pem  client-key.pem   ib_logfile0  mysql             performance_schema  school           sys
ca.pem      ib_buffer_pool   ib_logfile1  mysql-bin.000001  private_key.pem     server-cert.pem

#先进行完整性备份
[root@mysql01 ~]# mysqldump -uroot -p school > /opt/school.sql
Enter password:

#日志刷新生效
[root@mysql01 ~]# mysqladmin -uroot -p flush-logs
Enter password:
#新产生的mysql-bin.000002只记录上次刷新后的操作
[root@mysql01 ~]# ls /usr/local/mysql/data/
auto.cnf    client-cert.pem  ibdata1      ibtmp1            mysql-bin.000002    private_key.pem  server-cert.pem
ca-key.pem  client-key.pem   ib_logfile0  mysql             mysql-bin.index     public_key.pem   server-key.pem
ca.pem      ib_buffer_pool   ib_logfile1  mysql-bin.000001  performance_schema  school           sys

[root@mysql01 ~]# mysql -uroot -p
Enter password:
----------------------------------------
mysql> use school;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> select * from info;
+----+--------+-------+---------+-------+
| id | name   | score | address | hobby |
+----+--------+-------+---------+-------+
|  1 | 唐三   | 90.00 | 广州    |     1 |
|  2 | 叶凡   | 91.00 | 伦敦    |     2 |
|  4 | 曹操   | 66.50 | 合肥    |     4 |
+----+--------+-------+---------+-------+
3 rows in set (0.00 sec)

#再次插入数据生产增量备份
mysql> insert into info (name,score,address,hobby) values ('美猴王',75,'武汉',1);
Query OK, 1 row affected (0.00 sec)

mysql> exit
Bye

[root@mysql01 ~]# mysqladmin -uroot -p flush-log
Enter password:
#新产生mysql-bin.000003日志记录insert操作
[root@mysql01 ~]# ls /usr/local/mysql/data/
auto.cnf    client-cert.pem  ibdata1      ibtmp1            mysql-bin.000002  performance_schema  school           sys
ca-key.pem  client-key.pem   ib_logfile0  mysql             mysql-bin.000003  private_key.pem     server-cert.pem
ca.pem      ib_buffer_pool   ib_logfile1  mysql-bin.000001  mysql-bin.index   public_key.pem      server-key.pem

[root@mysql01 ~]# mysql -uroot -p
Enter password:
---------------------------------------------------------------
mysql> use school;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> insert into info (name,score,address,hobby) values ('超人',83,'上海',2);
Query OK, 1 row affected (0.00 sec)

mysql> select * from info;
+----+-----------+-------+---------+-------+
| id | name      | score | address | hobby |
+----+-----------+-------+---------+-------+
|  1 | 唐三      | 90.00 | 广州    |     1 |
|  2 | 叶凡      | 91.00 | 伦敦    |     2 |
|  4 | 曹操      | 66.50 | 合肥    |     4 |
|  5 | 美猴王    | 75.00 | 武汉    |     1 |
|  6 | 超人      | 83.00 | 上海    |     2 |
+----+-----------+-------+---------+-------+
5 rows in set (0.00 sec)

mysql> exit
Bye

#刷新日志生效
[root@mysql01 ~]# mysqladmin -uroot -p flush-log
Enter password:

#环境准备
[root@mysql01 ~]# mysql -uroot -p
Enter password:
--------------------------------------------------------------
mysql> use school;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed

#删除内容
mysql> delete from info where id=6;
Query OK, 1 row affected (0.00 sec)

mysql> delete from info where id=5;
Query OK, 1 row affected (0.01 sec)

mysql> select * from info;
+----+--------+-------+---------+-------+
| id | name   | score | address | hobby |
+----+--------+-------+---------+-------+
|  1 | 唐三   | 90.00 | 广州    |     1 |
|  2 | 叶凡   | 91.00 | 伦敦    |     2 |
|  4 | 曹操   | 66.50 | 合肥    |     4 |
+----+--------+-------+---------+-------+
3 rows in set (0.00 sec)

mysql> exit
Bye
[root@mysql01 ~]# ls /usr/local/mysql/data/
auto.cnf    client-cert.pem  ibdata1      ibtmp1            mysql-bin.000002  mysql-bin.index     public_key.pem   server-key.pem
ca-key.pem  client-key.pem   ib_logfile0  mysql             mysql-bin.000003  performance_schema  school           sys
ca.pem      ib_buffer_pool   ib_logfile1  mysql-bin.000001  mysql-bin.000004  private_key.pem     server-cert.pem

#查看日志文件,vim看日志是乱码
[root@mysql01 ~]# mysqlbinlog --no-defaults --base64-output=decode-rows -v /usr/local/mysql/data/mysql-bin.000003
[root@mysql01 ~]# mysqlbinlog --no-defaults --base64-output=decode-rows -v /usr/local/mysql/data/mysql-bin.000004

#恢复操作,恢复时如果被拒绝,是有其他mysql进程占用了
[root@mysql01 ~]# mysqlbinlog --no-defaults /usr/local/mysql/data/mysql-bin.000003 | mysql -uroot -p
Enter password:

#验证
[root@web-server ~]# mysql -uroot -p
Enter password:
---------------------------------------------------------------
mysql> select * from info;
+----+--------+-------+---------+-------+
| id | name   | score | address | hobby |
+----+--------+-------+---------+-------+
|  1 | 唐三   | 90.00 | 广州    |     1 |
|  2 | 叶凡   | 91.00 | 伦敦    |     2 |
|  4 | 曹操   | 66.50 | 合肥    |     4 |
|  6 | 超人   | 83.00 | 上海    |     2 |
+----+--------+-------+---------+-------+
4 rows in set (0.00 sec)

2.主从复制和读写分离

必须记住 3 个核心组件

  1. binlog(二进制日志) —— 主库
  2. IO 线程 —— 从库
  3. SQL 线程 —— 从库

完整流程(一步一步,逐句理解)

  1. 主库执行增删改(insert/update/drop)
  2. MySQL 把这些操作记录到 binlog 日志文件
  3. 从库的 IO 线程连接主库,请求 binlog
  4. 主库的 dump 线程把 binlog 发给从库
  5. 从库 IO 线程将内容写到本地 relay log(中继日志)
  6. 从库 SQL 线程读取中继日志,重放 SQL 语句
  7. 两个 Yes 代表正常:IO_Running、SQL_Running
  8. 从库数据和主库完全一致

使用目标:数据冗余和灾难恢复;提升并发能力、避免锁冲突。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

MySQL读写分离原理

  • 只在主服务器上写,只在从服务器上读

  • 主数据库处理事务性查询,从数据库处理SELECT查询

  • 数据库复制用于将事务性查询的变更同步到集群中的从数据库

  • 读写分离方案

    • 基于程序代码内部实现
    • 基于中间代理层实现
      • MySQL-Proxy
      • Amoeba

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

  • 在每个事务更新数据完成之前,Master将这些改变记录进二进制日志。写入二进制日志完成后,Master通知存储引擎提交事务。
  • Slave将Master 的 Binary log复制到其中继日志(Relay log)。首先,Slave开始一个工作线程-I/0线程,I/0线程在Master上打开一个普通的连接,然后开始Binlog dump process。Binlog dump process从Master 的二进制日志中读取事件,如果已经跟上Master,它会睡眠并等待Master产生新的事件。I/0线程将这些事件写入中继日志。
  • SQLslavethread(SQL从线程)处理该过程的最后一步。SQL线程从中继日志读取事件,并重放其中的事件而更新Slave数据,使其与Master中的数据保持一致。只要该线程与I/0线程保持一致,中继日志通常会位于0S的缓存中,所以中继日志的开销很小。复制过程有一个很重要的限制,即复制在Slave上是串行化的,也就是说Master上的并行更新操作不能在Slave上并行操作。

实验拓扑图

使用Centos-7-template模板克隆产生应用客户端和amoeba

使用mysql模板克隆产生mysql主服务器,mysql从节点1,mysql从节点2

根据下表,将IP地址,主机名更改好

主机名 IP地址 作用
mysql-master 192.168.108.101 mysql主服务器
mysql-slave01 192.168.108.102 mysql从节点1
mysql-slave02 192.168.108.103 mysql从节点2
amoeba 192.168.108.110 amoeba
mysql-client 192.168.108.111 应用客户端

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

时间同步

通过时间戳实现业务的一致性

# 所有节点
ntpdate ntp.aliyun.com
date -R

systemctl disable firewalld --now
setenforce 0

故障:使用此方法,对时完成后,无法重启mysqld服务

原因:之前在windows端使用navicat连接过mysql

解决:pkill -9 mysql;systemctl restart mysqld

mysql主从服务器配置

mysql主服务器配置

[root@mysql-master ~]# vim /etc/my.cnf
server-id = 11
log-bin = master-bin                         #主服务器日志文件
log-slave-updates = true                     #从服务器更新二进制日志

[root@mysql-master ~]# systemctl restart mysqld

[root@mysql-master ~]# mysql -u root -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 7
Server version: 5.7.17-log Source distribution

Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.

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> GRANT REPLICATION SLAVE ON *.* TO 'myslave'@'192.168.108.%' IDENTIFIED BY '123456';
Query OK, 0 rows affected, 1 warning (0.01 sec)

mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)

mysql> show master status;
+-------------------+----------+--------------+------------------+-------------------+
| File              | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+-------------------+----------+--------------+------------------+-------------------+
| master-bin.000001 |      604 |              |                  |                   |
+-------------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)

#检查有没有master-bin.000001
[root@mysql-master ~]# ls /usr/local/mysql/data
auto.cnf        ibdata1      ib_logfile1  master-bin.000001  mysql               sys
ib_buffer_pool  ib_logfile0  ibtmp1       master-bin.index   performance_schema

mysql从服务器配置

mysql-slave01,mysql-slave02都要做如下操作

#主从是克隆的要做这个操作,否则UUID一致
[root@mysql-slave01 ~]# systemctl stop mysqld
[root@mysql-slave01 ~]# rm -f /usr/local/mysql/data/auto.cnf
[root@mysql-slave01 ~]# systemctl start mysqld

[root@mysql-slave01 ~]# vim /etc/my.cnf
server-id = 22                                     #另外一台为23
relay-log = relay-log-bin                          #从主服务器上同步日志文件记录到本地
relay-log-index = slave-relay-bin.index           #定义relay-log的位置和名称

[root@mysql-slave01 ~]# systemctl restart mysqld

[root@mysql-slave01 ~]# mysql -u root -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.7.17 Source distribution

Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.

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> change master to master_host='192.168.108.101',master_user='myslave',master_password='123456',master_log_file='master-bin.000001',master_log_pos=604;              #master_log_file,master_log_pos与前面查询的相同
Query OK, 0 rows affected, 2 warnings (0.03 sec)

mysql> start slave;
Query OK, 0 rows affected (0.02 sec)

mysql> show slave status\G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.108.101
                  Master_User: myslave
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: master-bin.000001
          Read_Master_Log_Pos: 604
               Relay_Log_File: relay-log-bin.000002
                Relay_Log_Pos: 321
        Relay_Master_Log_File: master-bin.000001
             Slave_IO_Running: Yes                  #Yes
            Slave_SQL_Running: Yes                  #Yes
              Replicate_Do_DB:
          Replicate_Ignore_DB:
           Replicate_Do_Table:
       Replicate_Ignore_Table:
      Replicate_Wild_Do_Table:
  Replicate_Wild_Ignore_Table:
                   Last_Errno: 0
                   Last_Error:
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 604
              Relay_Log_Space: 526
              Until_Condition: None
               Until_Log_File:
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File:
           Master_SSL_CA_Path:
              Master_SSL_Cert:
            Master_SSL_Cipher:
               Master_SSL_Key:
        Seconds_Behind_Master: 0
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error:
               Last_SQL_Errno: 0
               Last_SQL_Error:
  Replicate_Ignore_Server_Ids:
             Master_Server_Id: 11
                  Master_UUID: 5d895caf-a1e0-11f0-b3ec-000c29866c0f
             Master_Info_File: /usr/local/mysql/data/master.info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: Slave has read all relay log; waiting for more updates
           Master_Retry_Count: 86400
                  Master_Bind:
      Last_IO_Error_Timestamp:
     Last_SQL_Error_Timestamp:
               Master_SSL_Crl:
           Master_SSL_Crlpath:
           Retrieved_Gtid_Set:
            Executed_Gtid_Set:
                Auto_Position: 0
         Replicate_Rewrite_DB:
                 Channel_Name:
           Master_TLS_Version:
1 row in set (0.00 sec)

ERROR:
No query specified

#mysql-slave02
[root@mysql-slave02 ~]# systemctl stop mysqld
[root@mysql-slave02 ~]# rm -f /usr/local/mysql/data/auto.cnf
[root@mysql-slave02 ~]# systemctl start mysqld

[root@mysql-slave02 ~]# vim /etc/my.cnf
server-id = 23
relay-log = relay-log-bin                         
relay-log-index = slave-relay-bin.index

[root@mysql-slave02 ~]# systemctl restart mysqld

[root@mysql-slave02 ~]# mysql -u root -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.7.17 Source distribution

Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.

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> change master to master_host='192.168.108.101',master_user='myslave',master_password='123456',master_log_file='master-bin.000001',master_log_pos=604;
Query OK, 0 rows affected, 2 warnings (0.04 sec)

mysql> start slave;
Query OK, 0 rows affected (0.01 sec)

mysql> show slave status\G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.108.101
                  Master_User: myslave
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: master-bin.000001
          Read_Master_Log_Pos: 604
               Relay_Log_File: relay-log-bin.000002
                Relay_Log_Pos: 321
        Relay_Master_Log_File: master-bin.000001
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB:
          Replicate_Ignore_DB:
           Replicate_Do_Table:
       Replicate_Ignore_Table:
      Replicate_Wild_Do_Table:
  Replicate_Wild_Ignore_Table:
                   Last_Errno: 0
                   Last_Error:
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 604
              Relay_Log_Space: 526
              Until_Condition: None
               Until_Log_File:
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File:
           Master_SSL_CA_Path:
              Master_SSL_Cert:
            Master_SSL_Cipher:
               Master_SSL_Key:
        Seconds_Behind_Master: 0
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error:
               Last_SQL_Errno: 0
               Last_SQL_Error:
  Replicate_Ignore_Server_Ids:
             Master_Server_Id: 11
                  Master_UUID: 5d895caf-a1e0-11f0-b3ec-000c29866c0f
             Master_Info_File: /usr/local/mysql/data/master.info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: Slave has read all relay log; waiting for more updates
           Master_Retry_Count: 86400
                  Master_Bind:
      Last_IO_Error_Timestamp:
     Last_SQL_Error_Timestamp:
               Master_SSL_Crl:
           Master_SSL_Crlpath:
           Retrieved_Gtid_Set:
            Executed_Gtid_Set:
                Auto_Position: 0
         Replicate_Rewrite_DB:
                 Channel_Name:
           Master_TLS_Version:
1 row in set (0.00 sec)

ERROR:
No query specified

mysql-slave01,mysql-slave02查询结果如下

image-20251013222601673

验证主从同步

# 主服务器上:
[root@mysql-master ~]# mysql -uroot -phuawei
mysql> create database school;
Query OK, 1 row affected (0.01 sec)
mysql> use school;

CREATE TABLE student (
id int UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(20) NOT NULL,
age tinyint UNSIGNED,
#height DECIMAL(5,2),
gender ENUM('M','F') default 'M'
)ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4;

mysql> insert student (name,age)values('路飞',20);

# 去从服务器上 show databases;
[root@mysql-slave01 ~]# mysql -uroot -phuawei
mysql> select * from school.student;
+----+--------+------+--------+
| id | name   | age  | gender |
+----+--------+------+--------+
| 10 | 路飞   |   20 | M      |
+----+--------+------+--------+
1 row in set (0.00 sec)

amoeba服务器

#普通linux克隆
[root@amoeba ~]# hostnamectl set-hostname amoeba
[root@amoeba ~]# systemctl stop firewalld.service
[root@amoeba ~]# setenforce 0

[root@amoeba ~]# chmod +x jdk-6u14-linux-x64.bin
[root@amoeba ~]# ./jdk-6u14-linux-x64.bin
到yes的时候,输入yes按enter

[root@amoeba ~]# mv jdk1.6.0_14/ /usr/local/jdk1.6

[root@amoeba ~]# vim /etc/profile
最下面加
export JAVA_HOME=/usr/local/jdk1.6                   #java家目录
export CLASSPATH=$CLASSPATH:$JAVA_HOME/lib:$JAVA_HOME/jre/lib             #类环境和jre
export PATH=$JAVA_HOME/lib:$JAVA_HOME/jre/bin/:$PATH:$HOME/bin          
export AMOEBA_HOME=/usr/local/amoeba                  #指定amoeba路径
export PATH=$PATH:$AMOEBA_HOME/bin

[root@amoeba ~]# source /etc/profile

[root@amoeba ~]# mkdir /usr/local/amoeba

[root@amoeba ~]# tar zxvf amoeba-mysql-binary-2.2.0.tar.gz -C /usr/local/amoeba/

[root@amoeba ~]# chmod -R 755 /usr/local/amoeba/

#执行结果显示amoeba start|stop说明安装成功
[root@amoeba ~]# /usr/local/amoeba/bin/amoeba
amoeba start|stop

在三台mysql上添加权限开放给amoeba访问

#amooba访问数据库的账号 
#mysql-master
mysql> grant all on *.* to test@'192.168.108.%' identified by '123.com';

#mysql-slave01
mysql> grant all on *.* to test@'192.168.108.%' identified by '123.com';

#mysql-slave02
mysql> grant all on *.* to test@'192.168.108.%' identified by '123.com';

回到amoeba服务器

[root@amoeba ~]# cd /usr/local/amoeba/
[root@amoeba amoeba]# vim conf/amoeba.xml
---30行--
 <property name="user">amoeba</property           #客户端访问amoeba账号
----32行---------
 <property name="password">123456</property>        #客户端访问ameoba密码

---117和120-去掉注释-
 115<property name="defaultPool">master</property>
 116
 117
 118<property name="writePool">master</property>
 119<property name="readPool">slaves</property>
 120

[root@amoeba amoeba]# vim conf/dbServers.xml         #数据库配置
---23--注意!!!(mysql5.7,默认没有test数据库所以需要修改为mysql数据库)-(mysql5.5直接忽略)--
<!-- mysql schema -->
<property name="schema">mysql</property>

--25行到30行,第30行-->移动到28行后面
 25                         <!-- mysql user -->
 26                         <property name="user">test</property>
 27
 28                         <!--  mysql password -->
 29                         <property name="password">123.com</property>
 30

-----45到50行主服务器地址---
45<dbServer name="master"  parent="abstractServer">
48<property name="ipAddress">192.168.108.101</property>
--52到57行从服务器主机名-
52<dbServer name="slave1"  parent="abstractServer">
--55-从服务器地址-
55 <property name="ipAddress">192.168.108.102</property>
 ---52到57行复制一份在58行后面
原52行<dbServer name="slave2"  parent="abstractServer">
--55-从服务器地址-
原55 <property name="ipAddress">192.168.108.103</property>
 
 ---仅跟在上面的配置后面,multiPool行(本来就有,修改)
 <dbServer name="slaves" virtual="true">
 <poolConfig class="com.meidusa.amoeba.server.MultipleServerPool   #不改

<property name="poolNames">slave1,slave2</property>
 </poolConfig>           #不改

[root@amoeba ~]# /usr/local/amoeba/bin/amoeba start&
[1] 33499

[root@amoeba ~]# netstat -anpt | grep java
tcp6       0      0 :::8066                 :::*                    LISTEN      33499/java
tcp6       0      0 127.0.0.1:21128         :::*                    LISTEN      33499/java
tcp6       0      0 192.168.108.110:41754   192.168.108.101:3306    ESTABLISHED 33499/java
tcp6       0      0 192.168.108.110:41722   192.168.108.102:3306    ESTABLISHED 33499/java
tcp6       0      0 192.168.108.110:36956   192.168.108.103:3306    ESTABLISHED 33499/java

vim conf/dbServers.xml 结果如下

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

测试客户端

[root@mysql-client ~]# yum install -y mysql
[root@mysql-client ~]# mysql -u amoeba -p123456 -h 192.168.108.110 -P8066     #连接amoeba服务器,8086端口在amoeba上执行netstat -anpt|grep java看
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MySQL connection id is 927449563
Server version: 5.1.45-mysql-amoeba-proxy-2.2.0

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MySQL [(none)]>

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

MASTER

[root@mysql-master ~]# mysql -u root -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 10
Server version: 5.7.17-log Source distribution

Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.

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> use school;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> insert student (name,age)values('鸣人',20);
Query OK, 1 row affected (0.00 sec)

#此时会同步
#mysql-slave01
mysql> select * from student;
+----+--------+------+--------+
| id | name   | age  | gender |
+----+--------+------+--------+
| 10 | 路飞  |   20 | M      |
| 11 | 鸣人   |   20 | M      |
+----+--------+------+--------+
2 rows in set (0.00 sec)

#mysql-slave02
mysql> select * from student;
+----+--------+------+--------+
| id | name   | age  | gender |
+----+--------+------+--------+
| 10 | 路飞  |   20 | M      |
| 11 | 鸣人   |   20 | M      |
+----+--------+------+--------+
2 rows in set (0.00 sec)

在两台从上

# mysql-slave01
mysql> stop slave;

# mysql-slave02
mysql> stop slave;

在客户端上插入数据,内容不会同步

#mysql-client上添加,由于不会同步,只有mysql-master192.168.108.101节点有该记录
# mysql-client
MySQL [school]> insert student (name,age)values('卡卡西',30);

在mysql-slave01上

#mysql-slave01
mysql> use school;
mysql> insert student (name,age)values('卡卡西',31);

mysql-slave02上

# mysql-slave02
mysql> use school;
mysql> insert student (name,age)values('卡卡西',32);

验证主从复制

在mysql-slave01和mysql-slave02上查看

# mysql-slave01
mysql> select * from student;
+----+-----------+------+--------+
| id | name      | age  | gender |
+----+-----------+------+--------+
| 10 | 路飞      |   20 | M      |
| 11 | 鸣人      |   20 | M      |
| 12 | 卡卡西    |   31 | M      |
+----+-----------+------+--------+
3 rows in set (0.00 sec)

#mysql-slave02
mysql> select * from student;
+----+-----------+------+--------+
| id | name      | age  | gender |
+----+-----------+------+--------+
| 10 | 路飞      |   20 | M      |
| 11 | 鸣人      |   20 | M      |
| 12 | 卡卡西    |   32| M      |
+----+-----------+------+--------+
3 rows in set (0.00 sec)

并没有将客户端写入的insert student (name,age)values(‘卡卡西’,30);同步

在mysq-master上查看内容发现写入成功:

# mysql-master
mysql> select * from student;
+----+-----------+------+--------+
| id | name      | age  | gender |
+----+-----------+------+--------+
| 10 | 路飞      |   20 | M      |
| 11 | 鸣人      |   20 | M      |
| 12 | 卡卡西    |   30 | M      |
+----+-----------+------+--------+
3 rows in set (0.00 sec)

验证读写分离

在客户端上测试,第一次会向从服务器1读数,据-第二次会向从2读取

#mysql-client
MySQL [(none)]> select * from school.student;
+----+-----------+------+--------+
| id | name      | age  | gender |
+----+-----------+------+--------+
| 10 | 路飞      |   20 | M      |
| 11 | 鸣人      |   20 | M      |
| 12 | 卡卡西    |   31 | M      |
+----+-----------+------+--------+
3 rows in set (0.02 sec)

MySQL [(none)]> select * from school.student;
+----+-----------+------+--------+
| id | name      | age  | gender |
+----+-----------+------+--------+
| 10 | 路飞      |   20 | M      |
| 11 | 鸣人      |   20 | M      |
| 12 | 卡卡西    |   32 | M      |
+----+-----------+------+--------+
3 rows in set (0.00 sec)
#都是从从节点读取的,读写分离,由实验结果可知:客户端的读取内容会从mysql-slave01和mysql-slave02上轮询得到。

3.MHA高可用

  • 传统的MySQL主从架构存在的问题
    • 单点故障

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

案例前置知识点

  • MHA概述

    • 一套优秀的MySQL高可用环境下故障切换和主从复制的软件
    • MySQL故障过程中,MHA能做到0-30秒内自动完成故障切换
  • MHA的组成

    • MHA Manager(管理节点)
    • MHA Node(数据节点)
  • MHA特点

    • 自动故障切换过程中,MHA试图从宕机的主服务器上保存
    • 二进制日志,最大程度的保证数据不丢失
    • 使用半同步复制,可以大大降低数据丢失的风险
    • 目前MHA支持一主多从架构,最少三台服务,即一主两从

使用场景:自动故障转移(Failover)和主从切换(Switchover)

实验拓扑图

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

实验思路

1.MHA架构
1)数据库安装
2)一主两从
3)MHA搭建

2.故障模拟
1)主库失效
2)备选主库成为主库
3)从库2将备选主库指向为主库

案例环境

  1. 本案例环境

使用centos模板克隆产生mha节点
使用mysql模板克隆产生mysql-master,mysql-slave01,mysql-slave02

根据下表,将IP地址,主机名更改好

主机名 IP地址 作用
mysql-master 192.168.108.131 mysql主服务器,安装node组件
mysql-slave01 192.168.108.132 mysql从节点1,安装node组件
mysql-slave02 192.168.108.133 mysql从节点2,安装node组件
mha 192.168.108.130 amoeba,安装node组件、manager组件

这里操作系统是 CentOS7 版本,所以这里下载 MHA 版本是 0.57 版本。

  1. 案例需求
    本案例要求通过 MHA 监控 MySQL 数据库在故障时进行自动切换,不影响业务。
  2. 案例实现思路
    1) 安装 MySQL 数据库
    2) 配置 MySQL 一主两从
    3) 安装 MHA 软件
    4) 配置无密码认证
    5) 配置 MySQL MHA 高可用
    6) 模拟 master 故障切换

在三台 MySQL 节点上分别安装前置环境

#主从是克隆的要做这个操作,否则UUID一致
[root@mysql-slave01 ~]# systemctl stop mysqld
[root@mysql-slave01 ~]# rm -f /usr/local/mysql/data/auto.cnf
[root@mysql-slave01 ~]# systemctl start mysqld

[root@mysql-slave02 ~]# systemctl stop mysqld
[root@mysql-slave02 ~]# rm -f /usr/local/mysql/data/auto.cnf
[root@mysql-slave02 ~]# systemctl start mysqld

安装编译依赖的环境

#mysql-master,mysql-slave01,mysql-slave02配置
[root@mysql-master ~]# yum -y install perl-Module-Install
[root@mysql-slave01 ~]# yum -y install perl-Module-Install
[root@mysql-slave02 ~]# yum -y install perl-Module-Install

修改 Master 的主配置文件/etc/my.cnf 文件

[root@mysql-master ~]# vim /etc/my.cnf
[mysqld]
server-id = 1                     #三台服务器的 server-id 不能一样
log_bin = master-bin
log-slave-updates = true

配置从服务器:
在/etc/my.cnf 中修改或者增加下面内容。

#mysql-slave01,请注释/etc/my.cnf 中 [client]下 #default-character-set=utf8
[root@mysql-slave01 ~]# vim /etc/my.cnf         #下面只列出了要改的内容
[client]
#default-character-set=utf8

[mysqld]
server-id = 2           
log_bin = master-bin                
relay-log = relay-log-bin 
relay-log-index = slave-relay-bin.index 

#mysql-slave02,请注释/etc/my.cnf 中 [client]下 #default-character-set=utf8
[root@mysql-slave02 ~]# vim /etc/my.cnf
[client]
#default-character-set=utf8

[mysqld]
server-id = 3                    
relay-log = relay-log-bin 
relay-log-index = slave-relay-bin.index 

三节点都要操作

[root@mysql-master ~]# ln -s /usr/local/mysql/bin/mysqlbinlog /usr/bin/
[root@mysql-master ~]# ln -s /usr/local/mysql/bin/mysql /usr/bin/
[root@mysql-master ~]# systemctl restart mysqld

[root@mysql-slave01 ~]# ln -s /usr/local/mysql/bin/mysqlbinlog /usr/bin/
[root@mysql-slave01 ~]# ln -s /usr/local/mysql/bin/mysql /usr/bin/
[root@mysql-slave01 ~]# systemctl restart mysqld

[root@mysql-slave02 ~]# ln -s /usr/local/mysql/bin/mysqlbinlog /usr/bin/
[root@mysql-slave02 ~]# ln -s /usr/local/mysql/bin/mysql /usr/bin/
[root@mysql-slave02 ~]# systemctl restart mysqld

[!IMPORTANT]

mysql5.7注意

请注释/etc/my.cnf 中 【client】下 #default-character-set=utf8

一定要注释,否则报错

ln -s /usr/local/mysql/bin/mysqlbinlog /usr/bin/
ln -s /usr/local/mysql/bin/mysql /usr/bin/

配置 MySQL 一主两从

MySQL 主从配置相对比较简单。需要注意的是授权。步骤如下:
在所有数据库节点上授权两个用户,一个是从库同步使用,另外一个是 manager 使用。

#mysql-master
mysql> grant replication slave on *.* to 'myslave'@'192.168.108.%' identified by '123';
mysql> grant all privileges on *.* to 'mha'@'192.168.108.%' identified by 'manager';
mysql> flush privileges;

#mysql-slave01
mysql> grant replication slave on *.* to 'myslave'@'192.168.108.%' identified by '123';
mysql> grant all privileges on *.* to 'mha'@'192.168.108.%' identified by 'manager';
mysql> flush privileges;

#mysql-slave02
mysql> grant replication slave on *.* to 'myslave'@'192.168.108.%' identified by '123';
mysql> grant all privileges on *.* to 'mha'@'192.168.108.%' identified by 'manager';
mysql> flush privileges;

下面三条授权按理论是不用添加的,但是做案例实验环境时候通过 MHA 检查MySQL 主从有报错,
报两个从库通过主机名连接不上主库,所以所有数据库加上下面的授权。

#mysql-master配置(mha@mysql-master与主机名相同)
mysql> grant all privileges on *.* to 'mha'@'mysql-master' identified by 'manager';       
mysql> grant all privileges on *.* to 'mha'@'mysql-slave01' identified by 'manager';
mysql> grant all privileges on *.* to 'mha'@'mysql-slave02' identified by 'manager';
mysql> flush privileges;

#mysql-slave01配置(mha@mysql-master与主机名相同)
mysql> grant all privileges on *.* to 'mha'@'mysql-master' identified by 'manager';       
mysql> grant all privileges on *.* to 'mha'@'mysql-slave01' identified by 'manager';
mysql> grant all privileges on *.* to 'mha'@'mysql-slave02' identified by 'manager';
mysql> flush privileges;

#mysql-slave02配置(mha@mysql-master与主机名相同)
mysql> grant all privileges on *.* to 'mha'@'mysql-master' identified by 'manager';       
mysql> grant all privileges on *.* to 'mha'@'mysql-slave01' identified by 'manager';
mysql> grant all privileges on *.* to 'mha'@'mysql-slave02' identified by 'manager';
mysql> flush privileges;

在mysql-master主机上查看二进制文件和同步点

mysql> show master status;
+-------------------+----------+--------------+------------------+-------------------+
| File              | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+-------------------+----------+--------------+------------------+-------------------+
| master-bin.000001 |     1897 |              |                  |                   |
+-------------------+----------+--------------+------------------+-------------------+

接下来在 mysql-slave01 和 mysql-slave02分别执行同步。

#mysql-slave01,命令中的master_log_pos的值,取决于msql-master show master status查看的Position
mysql> change master to master_host='192.168.108.131',master_user='myslave',master_password='123',master_log_file='master-bin.000001',master_log_pos=1897; 
mysql> start slave;

#mysql-slave02
mysql> change master to master_host='192.168.108.131',master_user='myslave',master_password='123',master_log_file='master-bin.000001',master_log_pos=1897; 
mysql> start slave;

查看 IO 和 SQL 线程都是 yes 代表同步是否正常

#mysql-slave01
mysql> show slave status\G;
Slave_IO_Running: Yes
Slave_SQL_Running: Yes

#mysql-slave02
mysql> show slave status\G;
Slave_IO_Running: Yes
Slave_SQL_Running: Yes

必须设置两个从库为只读模式:

#mysql-slave01
mysql> set global read_only=1;

#mysql-slave02
mysql> set global read_only=1;

注意:设置完成直接验证主从复制功能

安装 MHA 软件

所有服务器上都安装 MHA 依赖的环境,首先安装 epel 源。

#4个节点
# yum install epel-release --nogpgcheck -y

# yum install -y perl-DBD-MySQL \
perl-Config-Tiny \
perl-Log-Dispatch \
perl-Parallel-ForkManager \
perl-ExtUtils-CBuilder \
perl-ExtUtils-MakeMaker \
perl-CPAN

MHA 软件包对于每个操作系统版本不一样,这里 CentOS7.9 必须选择 0.57 版本,

在<注意:所有服务器>上必须先安装 node 组件,最后在 MHA 节点上安装 manager 组件,
因为 manager 依赖 node 组件。

#mysql-master
[root@mysql-master ~]# tar zxvf mha4mysql-node-0.57.tar.gz
[root@mysql-master ~]# cd mha4mysql-node-0.57
[root@mysql-master ~]# perl Makefile.PL
[root@mysql-master ~]# make
[root@mysql-master ~]# make install

#mysql-slave01
[root@mysql-slave01 ~]# tar zxvf mha4mysql-node-0.57.tar.gz
[root@mysql-slave01 ~]# cd mha4mysql-node-0.57
[root@mysql-slave01 ~]# perl Makefile.PL
[root@mysql-slave01 ~]# make
[root@mysql-slave01 ~]# make install

#mysql-slave02
[root@mysql-slave02 ~]# tar zxvf mha4mysql-node-0.57.tar.gz
[root@mysql-slave02 ~]# cd mha4mysql-node-0.57
[root@mysql-slave02 ~]# perl Makefile.PL
[root@mysql-slave02 ~]# make
[root@mysql-slave02 ~]# make install

#mha
[root@mha ~]# tar zxvf mha4mysql-node-0.57.tar.gz
[root@mha ~]# cd mha4mysql-node-0.57
[root@mha ~]# perl Makefile.PL
[root@mha ~]# make
[root@mha ~]# make install

在 MHA上安装 manager 组件(!注意:一定要先安装node 组件才能安装manager 组件)

#mha
[root@mha ~]# tar zxvf mha4mysql-manager-0.57.tar.gz
[root@mha ~]# cd mha4mysql-manager-0.57
[root@mha mha4mysql-manager-0.57]# perl Makefile.PL
[root@mha mha4mysql-manager-0.57]# make
[root@mha mha4mysql-manager-0.57]# make install

manager 安装后在/usr/local/bin 下面会生成几个工具,主要包括以下几个:
masterha_check_ssh 检查 MHA 的 SSH 配置状况
masterha_check_repl 检查 MySQL 复制状况
masterha_manger 启动 manager的脚本
masterha_check_status 检测当前 MHA 运行状态
masterha_master_monitor 检测 master 是否宕机
masterha_master_switch 控制故障转移(自动或者手动)
masterha_conf_host 添加或删除配置的 server 信息
masterha_stop 关闭manager

node 安装后也会在/usr/local/bin 下面会生成几个脚本(这些工具通常由 MHAManager 的脚本触发,无需人为操作)主要如下:

save_binary_logs 保存和复制 master 的二进制日志
apply_diff_relay_logs 识别差异的中继日志事件并将其差异的事件应用于其他的 slave
filter_mysqlbinlog 去除不必要的 ROLLBACK 事件(MHA 已不再使用这个工具)
purge_relay_logs 清除中继日志(不会阻塞 SQL 线程)

配置无密码认证

在 manager 上配置到所有数据库节点的无密码认证

[root@mha ~]# ssh-keygen -t rsa             #一路按回车键
[root@mha ~]# ssh-copy-id 192.168.108.131
[root@mha ~]# ssh-copy-id 192.168.108.132
[root@mha ~]# ssh-copy-id 192.168.108.133

在 mysql-master 上配置到数据库节点mysql-slave01和mysql-slave02的无密码认证

[root@mysql-master ~]# ssh-keygen -t rsa
[root@mysql-master ~]# ssh-copy-id 192.168.108.132
[root@mysql-master ~]# ssh-copy-id 192.168.108.133

在 mysql-slave01 上配置到数据库节点mysql-master和mysql-slave02的无密码认证

[root@mysql-slave01 ~]# ssh-keygen -t rsa
[root@mysql-slave01 ~]# ssh-copy-id 192.168.108.131
[root@mysql-slave01 ~]# ssh-copy-id 192.168.108.133

在 mysql-slave02 上配置到数据库节点mysql-master和mysql-slave01的无密码认证

[root@mysql-slave02 ~]# ssh-keygen -t rsa
[root@mysql-slave02 ~]# ssh-copy-id 192.168.108.131
[root@mysql-slave02 ~]# ssh-copy-id 192.168.108.132

配置 MHA

在 manager 节点上复制相关脚本到/usr/local/bin 目录。

[root@mha ~]# cp -ra /root/mha4mysql-manager-0.57/samples/scripts /usr/local/bin

#拷贝后会有四个执行文件
[root@mha ~]# ll /usr/local/bin/scripts/
总用量 32
-rwxr-xr-x 1 mysql mysql 3648 531 2015 master_ip_failover  #自动切换时 VIP 管理的脚本
-rwxr-xr-x 1 mysql mysql 9872 525 09:07 master_ip_online_change #在线切换时 vip 的管理
-rwxr-xr-x 1 mysql mysql 11867 531 2015 power_manager #故障发生后关闭主机的脚本
-rwxr-xr-x 1 mysql mysql 1360 531 2015 send_report #因故障切换后发送报警的脚本

复制上述的自动切换时 VIP 管理的脚本到/usr/local/bin 目录,这里使用脚本管理 VIP,

[root@mha ~]# cp /usr/local/bin/scripts/master_ip_failover /usr/local/bin

修改内容如下:(删除原有内容,直接复制)

#复制时,#号间一段段复制
[root@mha ~]# vim /usr/local/bin/master_ip_failover
#!/usr/bin/env perl
use strict;
use warnings FATAL => 'all';

use Getopt::Long;

my (
$command, $ssh_user, $orig_master_host, $orig_master_ip,
$orig_master_port, $new_master_host, $new_master_ip, $new_master_port
);
#############################添加内容部分#########################################
my $vip = '192.168.108.200';
my $brdc = '192.168.108.255';
my $ifdev = 'ens33';
my $key = '1';
my $ssh_start_vip = "/sbin/ifconfig ens33:$key $vip";
my $ssh_stop_vip = "/sbin/ifconfig ens33:$key down";
my $exit_code = 0;
#my $ssh_start_vip = "/usr/sbin/ip addr add $vip/24 brd $brdc dev $ifdev label $ifdev:$key;/usr/sbin/arping -q -A -c 1 -I $ifdev $vip;iptables -F;";
#my $ssh_stop_vip = "/usr/sbin/ip addr del $vip/24 dev $ifdev label $ifdev:$key";
##################################################################################
GetOptions(
'command=s' => \$command,
'ssh_user=s' => \$ssh_user,
'orig_master_host=s' => \$orig_master_host,
'orig_master_ip=s' => \$orig_master_ip,
'orig_master_port=i' => \$orig_master_port,
'new_master_host=s' => \$new_master_host,
'new_master_ip=s' => \$new_master_ip,
'new_master_port=i' => \$new_master_port,
);

exit &main();

sub main {

print "\n\nIN SCRIPT TEST====$ssh_stop_vip==$ssh_start_vip===\n\n";

if ( $command eq "stop" || $command eq "stopssh" ) {

my $exit_code = 1;
eval {
print "Disabling the VIP on old master: $orig_master_host \n";
&stop_vip();
$exit_code = 0;
};
if ($@) {
warn "Got Error: $@\n";
exit $exit_code;
}
exit $exit_code;
}
elsif ( $command eq "start" ) {

my $exit_code = 10;
eval {
print "Enabling the VIP - $vip on the new master - $new_master_host \n";
&start_vip();
$exit_code = 0;
};
if ($@) {
warn $@;
exit $exit_code;
}
exit $exit_code;
}
elsif ( $command eq "status" ) {
print "Checking the Status of the script.. OK \n";
exit 0;
}
else {
&usage();
exit 1;
}
}
sub start_vip() {
`ssh $ssh_user\@$new_master_host \" $ssh_start_vip \"`;
}
# A simple system call that disable the VIP on the old_master
sub stop_vip() {
`ssh $ssh_user\@$orig_master_host \" $ssh_stop_vip \"`;
}

sub usage {
print
"Usage: master_ip_failover --command=start|stop|stopssh|status --orig_master_host=host --orig_master_ip=ip --orig_master_port=port --new_master_host=host --new_master_ip=ip --new_master_port=port\n";
}

创建 MHA 软件目录并拷贝配置文件。

[root@mha ~]# mkdir /etc/masterha
[root@mha ~]# cp /root/mha4mysql-manager-0.57/samples/conf/app1.cnf /etc/masterha/
[root@mha ~]# vim /etc/masterha/app1.cnf
#全部删掉,替换
[server default]
manager_log=/var/log/masterha/app1/manager.log
manager_workdir=/var/log/masterha/app1
master_binlog_dir=/usr/local/mysql/data
#master_ip_failover_script=/usr/local/bin/master_ip_failover
master_ip_online_change_script=/usr/local/bin/master_ip_online_change
password=manager
ping_interval=1
remote_workdir=/tmp
repl_password=123
repl_user=myslave
secondary_check_script=/usr/local/bin/masterha_secondary_check -s 192.168.108.132 -s 192.168.108.133
shutdown_script=""
ssh_user=root
user=mha

[server1]
hostname=192.168.108.131
port=3306

[server2]
candidate_master=1
check_repl_delay=0
hostname=192.168.108.132
port=3306

[server3]
hostname=192.168.108.133
port=3306

配置文件解析

[server default]
manager_workdir=/var/log/masterha/app1.log               ##manager工作目录
manager_log=/var/log/masterha/app1/manager.log            #manager日志
master_binlog_dir=/usr/local/mysql/data/                #master保存binlog的位置,这里的路径要与master里配置的binlog的路径一致,以便mha能找到
#master_ip_failover_script= /usr/local/bin/master_ip_failover    #设置自动failover时候的切换脚本,也就是上边的那个脚本
master_ip_online_change_script= /usr/local/bin/master_ip_online_change  #设置手动切换时候的切换脚本
password=manager      #设置mysql中mha用户的密码
user=mha        #设置监控用户mha
ping_interval=1      #设置监控主库,发送ping包的时间间隔,默认是3秒,尝试三次没有回应的时候自动进行railover
remote_workdir=/tmp    #设置远端mysql在发生切换时binlog的保存位置
repl_password=123        #设置复制用户的密码
repl_user=myslave           #设置复制用户的用户
report_script=/usr/local/send_report      #设置发生切换后发送的报警的脚本
secondary_check_script=/usr/local/bin/masterha_secondary_check -s 192.168.108.132 -s 192.168.108.133
shutdown_script=""  #设置故障发生后关闭故障主机脚本(该脚本的主要作用是关闭主机防止发生脑裂,这里没有使用)
ssh_user=root      #设置ssh的登录用户名

[server1]
hostname=192.168.108.131
port=3306

[server2]
hostname=192.168.108.132
port=3306
candidate_master=1    #//设置为候选master,如果设置该参数以后,发生主从切换以后将会将此从库提升为主库,即使这个主库不是集群中事件最新的slave
check_repl_delay=0    #默认情况下如果一个slave落后master 100M的relay logs的话,MHA将不会选择该slave作为一个新的master,因为对于这个slave的恢复需要花费很长时间,通过设置check_repl_delay=0,MHA触发切换在选择一个新的master的时候将会忽略复制延时,这个参数对于设置了candidate_master=1的主机非常有用,因为这个候选主在切换的过程中一定是新的master

[server3]
hostname=192.168.108.133
port=3306

验证配置

测试 ssh 无密码认证,如果正常最后会输出 successfully,如下所示。

#检测SSH无密码认证
[root@mha ~]# masterha_check_ssh -conf=/etc/masterha/app1.cnf
Tue Oct  7 15:16:58 2025 - [warning] Global configuration file /etc/masterha_default.cnf not found. Skipping.
Tue Oct  7 15:16:58 2025 - [info] Reading application default configuration from /etc/masterha/app1.cnf..
Tue Oct  7 15:16:58 2025 - [info] Reading server configuration from /etc/masterha/app1.cnf..
Tue Oct  7 15:16:58 2025 - [info] Starting SSH connection tests..
Tue Oct  7 15:16:58 2025 - [debug]
Tue Oct  7 15:16:58 2025 - [debug]  Connecting via SSH from root@192.168.108.131(192.168.108.131:22) to root@192.168.108.132(192.168.108.132:22)..
Tue Oct  7 15:16:58 2025 - [debug]   ok.
Tue Oct  7 15:16:58 2025 - [debug]  Connecting via SSH from root@192.168.108.131(192.168.108.131:22) to root@192.168.108.133(192.168.108.133:22)..
Tue Oct  7 15:16:58 2025 - [debug]   ok.
Tue Oct  7 15:16:59 2025 - [debug]
Tue Oct  7 15:16:58 2025 - [debug]  Connecting via SSH from root@192.168.108.132(192.168.108.132:22) to root@192.168.108.131(192.168.108.131:22)..
Tue Oct  7 15:16:58 2025 - [debug]   ok.
Tue Oct  7 15:16:58 2025 - [debug]  Connecting via SSH from root@192.168.108.132(192.168.108.132:22) to root@192.168.108.133(192.168.108.133:22)..
Tue Oct  7 15:16:59 2025 - [debug]   ok.
Tue Oct  7 15:16:59 2025 - [debug]
Tue Oct  7 15:16:59 2025 - [debug]  Connecting via SSH from root@192.168.108.133(192.168.108.133:22) to root@192.168.108.131(192.168.108.131:22)..
Tue Oct  7 15:16:59 2025 - [debug]   ok.
Tue Oct  7 15:16:59 2025 - [debug]  Connecting via SSH from root@192.168.108.133(192.168.108.133:22) to root@192.168.108.132(192.168.108.132:22)..
Tue Oct  7 15:16:59 2025 - [debug]   ok.
Tue Oct  7 15:16:59 2025 - [info] All SSH connection tests passed successfully.

#检测下主从复制
[root@mha ~]# masterha_check_repl -conf=/etc/masterha/app1.cnf
Tue Oct  7 15:30:03 2025 - [warning] Global configuration file /etc/masterha_default.cnf not found. Skipping.
Tue Oct  7 15:30:03 2025 - [info] Reading application default configuration from /etc/masterha/app1.cnf..
Tue Oct  7 15:30:03 2025 - [info] Reading server configuration from /etc/masterha/app1.cnf..
Tue Oct  7 15:30:03 2025 - [info] MHA::MasterMonitor version 0.57.
Tue Oct  7 15:30:04 2025 - [info] GTID failover mode = 0
Tue Oct  7 15:30:04 2025 - [info] Dead Servers:
Tue Oct  7 15:30:04 2025 - [info] Alive Servers:
Tue Oct  7 15:30:04 2025 - [info]   192.168.108.131(192.168.108.131:3306)
Tue Oct  7 15:30:04 2025 - [info]   192.168.108.132(192.168.108.132:3306)
Tue Oct  7 15:30:04 2025 - [info]   192.168.108.133(192.168.108.133:3306)
Tue Oct  7 15:30:04 2025 - [info] Alive Slaves:
Tue Oct  7 15:30:04 2025 - [info]   192.168.108.132(192.168.108.132:3306)  Version=5.7.17-log (oldest major version between slaves) log-bin:enabled
Tue Oct  7 15:30:04 2025 - [info]     Replicating from 192.168.108.131(192.168.108.131:3306)
Tue Oct  7 15:30:04 2025 - [info]     Primary candidate for the new Master (candidate_master is set)
Tue Oct  7 15:30:04 2025 - [info]   192.168.108.133(192.168.108.133:3306)  Version=5.7.17 (oldest major version between slaves) log-bin:disabled
Tue Oct  7 15:30:04 2025 - [info]     Replicating from 192.168.108.131(192.168.108.131:3306)
Tue Oct  7 15:30:04 2025 - [info] Current Alive Master: 192.168.108.131(192.168.108.131:3306)
Tue Oct  7 15:30:04 2025 - [info] Checking slave configurations..
Tue Oct  7 15:30:04 2025 - [warning]  relay_log_purge=0 is not set on slave 192.168.108.132(192.168.108.132:3306).
Tue Oct  7 15:30:04 2025 - [warning]  relay_log_purge=0 is not set on slave 192.168.108.133(192.168.108.133:3306).
Tue Oct  7 15:30:04 2025 - [warning]  log-bin is not set on slave 192.168.108.133(192.168.108.133:3306). This host cannot be a master.
Tue Oct  7 15:30:04 2025 - [info] Checking replication filtering settings..
Tue Oct  7 15:30:04 2025 - [info]  binlog_do_db= , binlog_ignore_db=
Tue Oct  7 15:30:04 2025 - [info]  Replication filtering check ok.
Tue Oct  7 15:30:04 2025 - [info] GTID (with auto-pos) is not supported
Tue Oct  7 15:30:04 2025 - [info] Starting SSH connection tests..
Tue Oct  7 15:30:06 2025 - [info] All SSH connection tests passed successfully.
Tue Oct  7 15:30:06 2025 - [info] Checking MHA Node version..
Tue Oct  7 15:30:06 2025 - [info]  Version check ok.
Tue Oct  7 15:30:06 2025 - [info] Checking SSH publickey authentication settings on the current master..
Tue Oct  7 15:30:06 2025 - [info] HealthCheck: SSH to 192.168.108.131 is reachable.
Tue Oct  7 15:30:06 2025 - [info] Master MHA Node version is 0.57.
Tue Oct  7 15:30:06 2025 - [info] Checking recovery script configurations on 192.168.108.131(192.168.108.131:3306)..
Tue Oct  7 15:30:06 2025 - [info]   Executing command: save_binary_logs --command=test --start_pos=4 --binlog_dir=/usr/local/mysql/data --output_file=/tmp/save_binary_logs_test --manager_version=0.57 --start_file=master-bin.000002
Tue Oct  7 15:30:06 2025 - [info]   Connecting to root@192.168.108.131(192.168.108.131:22)..
  Creating /tmp if not exists..    ok.
  Checking output directory is accessible or not..
   ok.
  Binlog found at /usr/local/mysql/data, up to master-bin.000002
Tue Oct  7 15:30:06 2025 - [info] Binlog setting check done.
Tue Oct  7 15:30:06 2025 - [info] Checking SSH publickey authentication and checking recovery script configurations on all alive slave servers..
Tue Oct  7 15:30:06 2025 - [info]   Executing command : apply_diff_relay_logs --command=test --slave_user='mha' --slave_host=192.168.108.132 --slave_ip=192.168.108.132 --slave_port=3306 --workdir=/tmp --target_version=5.7.17-log --manager_version=0.57 --relay_log_info=/usr/local/mysql/data/relay-log.info  --relay_dir=/usr/local/mysql/data/  --slave_pass=xxx
Tue Oct  7 15:30:06 2025 - [info]   Connecting to root@192.168.108.132(192.168.108.132:22)..
  Checking slave recovery environment settings..
    Opening /usr/local/mysql/data/relay-log.info ... ok.
    Relay log found at /usr/local/mysql/data, up to relay-log-bin.000002
    Temporary relay log file is /usr/local/mysql/data/relay-log-bin.000002
    Testing mysql connection and privileges..mysql: [Warning] Using a password on the command line interface can be insecure.
 done.
    Testing mysqlbinlog output.. done.
    Cleaning up test file(s).. done.
Tue Oct  7 15:30:07 2025 - [info]   Executing command : apply_diff_relay_logs --command=test --slave_user='mha' --slave_host=192.168.108.133 --slave_ip=192.168.108.133 --slave_port=3306 --workdir=/tmp --target_version=5.7.17 --manager_version=0.57 --relay_log_info=/usr/local/mysql/data/relay-log.info  --relay_dir=/usr/local/mysql/data/  --slave_pass=xxx
Tue Oct  7 15:30:07 2025 - [info]   Connecting to root@192.168.108.133(192.168.108.133:22)..
  Checking slave recovery environment settings..
    Opening /usr/local/mysql/data/relay-log.info ... ok.
    Relay log found at /usr/local/mysql/data, up to relay-log-bin.000002
    Temporary relay log file is /usr/local/mysql/data/relay-log-bin.000002
    Testing mysql connection and privileges..mysql: [Warning] Using a password on the command line interface can be insecure.
 done.
    Testing mysqlbinlog output.. done.
    Cleaning up test file(s).. done.
Tue Oct  7 15:30:07 2025 - [info] Slaves settings check done.
Tue Oct  7 15:30:07 2025 - [info]
192.168.108.131(192.168.108.131:3306) (current master)
 +--192.168.108.132(192.168.108.132:3306)
 +--192.168.108.133(192.168.108.133:3306)

Tue Oct  7 15:30:07 2025 - [info] Checking replication health on 192.168.108.132..
Tue Oct  7 15:30:07 2025 - [info]  ok.
Tue Oct  7 15:30:07 2025 - [info] Checking replication health on 192.168.108.133..
Tue Oct  7 15:30:07 2025 - [info]  ok.
Tue Oct  7 15:30:07 2025 - [info] Checking master_ip_failover_script status:
Tue Oct  7 15:30:07 2025 - [info]   /usr/local/bin/master_ip_failover --command=status --ssh_user=root --orig_master_host=192.168.108.131 --orig_master_ip=192.168.108.131 --orig_master_port=3306


IN SCRIPT TEST====/sbin/ifconfig ens33:1 down==/sbin/ifconfig ens33:1 192.168.108.200===

Checking the Status of the script.. OK
Tue Oct  7 15:30:07 2025 - [info]  OK.
Tue Oct  7 15:30:07 2025 - [warning] shutdown_script is not defined.
Tue Oct  7 15:30:07 2025 - [info] Got exit code 0 (Not master dead).

MySQL Replicaxtion Health is OK.

第一次配置需要去master上手动开启虚拟IP

#注意:第一次配置需要去master上手动开启虚拟IP
[root@mysql-master ~]# /sbin/ifconfig ens33:1 192.168.108.200/24

启动 MHA

[root@mha ~]# nohup masterha_manager --conf=/etc/masterha/app1.cnf --remove_dead_master_conf --ignore_last_failover < /dev/null > /var/log/masterha/app1/manager.log 2>&1 &
[1] 48240

–remove_dead_master_conf 该参数代表当发生主从切换后,老的主库的 ip 将会从配置文件中移除。
–manger_log 日志存放位置。
–ignore_last_failover 在缺省情况下,如果 MHA 检测到连续发生宕机,且两次宕机间隔不足 8 小时的话,则不会进行 Failover,之所以这样限制是为了避免 ping-pong 效应。该参数代表忽略上次 MHA 触发切换产生的文件,默认情况下,MHA 发生切换后会在日志记目录,也就是上面设置的日志 app1.failover.complete 文件,下次再次切换的时候如果发现该目录下存在该文件将不允许触发切换,除非在第一次切换后收到删除该文件,为了方便,这里设置为-–ignore_last_failover。

查看 MHA 状态,可以看到当前的 master 是 mysql-master 节点。

[root@mha ~]# masterha_check_status --conf=/etc/masterha/app1.cnf
app1 (pid:48240) is running(0:PING_OK), master:192.168.108.131

查看 MHA 日志,也以看到当前的 master 是 192.168.108.131,如下所示。

[root@mha ~]# cat /var/log/masterha/app1/manager.log
......
Tue Oct  7 15:32:17 2025 - [info] Slaves settings check done.
Tue Oct  7 15:32:17 2025 - [info]
192.168.108.131(192.168.108.131:3306) (current master)
 +--192.168.108.132(192.168.108.132:3306)
 +--192.168.108.133(192.168.108.133:3306)

Tue Oct  7 15:32:17 2025 - [info] Checking master_ip_failover_script status:
Tue Oct  7 15:32:17 2025 - [info]   /usr/local/bin/master_ip_failover --command=status --ssh_user=root --orig_master_host=192.168.108.131 --orig_master_ip=192.168.108.131 --orig_master_port=3306


IN SCRIPT TEST====/sbin/ifconfig ens33:1 down==/sbin/ifconfig ens33:1 192.168.108.200===

Checking the Status of the script.. OK
Tue Oct  7 15:32:17 2025 - [info]  OK.
Tue Oct  7 15:32:17 2025 - [warning] shutdown_script is not defined.
Tue Oct  7 15:32:17 2025 - [info] Set master ping interval 1 seconds.
Tue Oct  7 15:32:17 2025 - [info] Set secondary check script: /usr/local/bin/masterha_secondary_check -s 192.168.108.132 -s 192.168.108.133
Tue Oct  7 15:32:17 2025 - [info] Starting ping health check on 192.168.108.131(192.168.108.131:3306)..
Tue Oct  7 15:32:17 2025 - [info] Ping(SELECT) succeeded, waiting until MySQL doesn't respond..
[root@mha ~]#

查看 mysql-master 的 VIP 地址 192.168.108.200 是否存在?,这个 VIP 地址不会因为
manager 节点停止 MHA 服务而消失。

[root@mysql-master ~]# ifconfig
ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.108.131  netmask 255.255.255.0  broadcast 192.168.108.255
        inet6 fe80::deb2:46ba:c54a:56ed  prefixlen 64  scopeid 0x20<link>
        ether 00:0c:29:43:0b:39  txqueuelen 1000  (Ethernet)
        RX packets 42430  bytes 22790429 (21.7 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 29947  bytes 9476691 (9.0 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

ens33:1: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.108.200  netmask 255.255.255.0  broadcast 192.168.108.255
        ether 00:0c:29:43:0b:39  txqueuelen 1000  (Ethernet)

验证

#mha节点A窗口操作
[root@mha ~]# tailf /var/log/masterha/app1/manager.log     //启用监控观察日志记录

#mysql-master节点操作
[root@mysql-master ~]# pkill -9 mysql         //查看master变化,看上面命令的日志

#回到mha节点A窗口观察日志
[root@mha ~]# tailf /var/log/masterha/app1/manager.log

IN SCRIPT TEST====/sbin/ifconfig ens33:1 down==/sbin/ifconfig ens33:1 192.168.108.200===

Checking the Status of the script.. OK
Tue Oct  7 15:32:17 2025 - [info]  OK.
Tue Oct  7 15:32:17 2025 - [warning] shutdown_script is not defined.
Tue Oct  7 15:32:17 2025 - [info] Set master ping interval 1 seconds.
Tue Oct  7 15:32:17 2025 - [info] Set secondary check script: /usr/local/bin/masterha_secondary_check -s 192.168.108.132 -s 192.168.108.133
Tue Oct  7 15:32:17 2025 - [info] Starting ping health check on 192.168.108.131(192.168.108.131:3306)..
Tue Oct  7 15:32:17 2025 - [info] Ping(SELECT) succeeded, waiting until MySQL doesn't respond..
Tue Oct  7 15:39:47 2025 - [warning] Got error on MySQL select ping: 2006 (MySQL server has gone away)
Tue Oct  7 15:39:47 2025 - [info] Executing secondary network check script: /usr/local/bin/masterha_secondary_check -s 192.168.108.132 -s 192.168.108.133  --user=root  --master_host=192.168.108.131  --master_ip=192.168.108.131  --master_port=3306 --master_user=mha --master_password=manager --ping_type=SELECT
Tue Oct  7 15:39:47 2025 - [info] Executing SSH check script: save_binary_logs --command=test --start_pos=4 --binlog_dir=/usr/local/mysql/data --output_file=/tmp/save_binary_logs_test --manager_version=0.57 --binlog_prefix=master-bin
Tue Oct  7 15:39:47 2025 - [info] HealthCheck: SSH to 192.168.108.131 is reachable.
Master is reachable from 192.168.108.132!
Tue Oct  7 15:39:47 2025 - [warning] Master is reachable from at least one of other monitoring servers. Failover should not happen.
Tue Oct  7 15:39:48 2025 - [info] Ping(SELECT) succeeded, waiting until MySQL doesn't respond..

mha节点观察日志如下

pkill -9 mysql,mysqld短暂暂停又会启动

从 其他节点依然能够访问master,不会主从切换

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

故障模拟

在主库上:

# master 停止mysql观察现象
[root@mysql-master ~]# systemctl stop mysqld   
# master切换成功

可以看到从库的状态,其中之一肯定有切换到主库的
切换备选主库的算法:
1.一般判断从库的是从(position/GTID)判断优劣,数据有差异,最接近于master的slave,成为备选主。
2.数据一致的情况下,按照配置文件顺序,选择备选主库。
3.设定有权重(candidate_master=1),按照权重强制指定备选主。
1)默认情况下如果一个slave落后master 100M的relay logs的话,即使有权重,也会失效。
2)如果check_repl_delay=0的话,即使落后很多日志,也强制选择其为备选主。

故障修复

1.修复db

[root@mysql-master ~]# systemctl start mysqld  

修复主从

让slave01(备用master)成为master,让原master变成slave01

# mysql-slave01
mysql> show master status;
+-------------------+----------+--------------+------------------+-------------------+
| File              | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+-------------------+----------+--------------+------------------+-------------------+
| master-bin.000002 |     2210 |              |                  |                   |
+-------------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)

# mysql-master操作
mysql> change master to master_host='192.168.108.132',master_user='myslave',master_password='123',master_log_file='master-bin.000002',master_log_pos=2210;       #这里的master_log_pos写mysq_slave01的
mysql> start slave;

继续查看

#mysql-master
mysql> show slave status\G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.108.132         ---#主切换到了mysql-slave01
                  Master_User: myslave
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: master-bin.000002
          Read_Master_Log_Pos: 2210
               Relay_Log_File: mysql1-relay-bin.000002
                Relay_Log_Pos: 321
        Relay_Master_Log_File: master-bin.000002
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB:
          Replicate_Ignore_DB:
           Replicate_Do_Table:
       Replicate_Ignore_Table:
      Replicate_Wild_Do_Table:
  Replicate_Wild_Ignore_Table:
                   Last_Errno: 0
                   Last_Error:
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 2210
              Relay_Log_Space: 529
              Until_Condition: None
               Until_Log_File:
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File:
           Master_SSL_CA_Path:
              Master_SSL_Cert:
            Master_SSL_Cipher:
               Master_SSL_Key:
        Seconds_Behind_Master: 0
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error:
               Last_SQL_Errno: 0
               Last_SQL_Error:
  Replicate_Ignore_Server_Ids:
             Master_Server_Id: 2
                  Master_UUID: 865eeb1e-a383-11f0-8a5b-000c292673c8
             Master_Info_File: /usr/local/mysql/data/master.info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: Slave has read all relay log; waiting for more updates
           Master_Retry_Count: 86400
                  Master_Bind:
      Last_IO_Error_Timestamp:
     Last_SQL_Error_Timestamp:
               Master_SSL_Crl:
           Master_SSL_Crlpath:
           Retrieved_Gtid_Set:
            Executed_Gtid_Set:
                Auto_Position: 0
         Replicate_Rewrite_DB:
                 Channel_Name:
           Master_TLS_Version:
1 row in set (0.00 sec)

ERROR:
No query specified

4.MySQL 事务详解(ACID 四大特性)

事务是一组不可分割的 SQL 操作集合,核心是 ACID 四大特性,保障数据可靠性。

1.1 事务四大特性(ACID)

(1)原子性(Atomicity)

事务不可分割,要么全部执行成功提交,要么全部失败回滚,依赖 undo log 实现回滚。

(2)一致性(Consistency)

事务执行前后,数据库数据完整性约束不被破坏,是事务的最终目标。

(3)隔离性(Isolation)

多事务并发执行时互不干扰,MySQL 通过隔离级别平衡隔离性与并发性能,解决脏读、不可重复读、幻读问题。

4种隔离级别(从低到高):读未提交、读已提交(RC)、可重复读(RR,MySQL 默认)、串行化。

(4)持久性(Durability)

事务提交后,修改永久保存,即使 MySQL 崩溃也不会丢失,依赖 redo log 实现。

1.2 核心补充

InnoDB 依赖 MVCC(多版本并发控制)、read view 实现隔离性,通过锁机制解决写-写并发冲突;事务相关日志(redo log、undo log、binlog)各司其职,保障事务正常运行。

5.MySQL 索引核心原理与优化

索引是提升查询性能的核心,本质是 B+树数据结构,减少磁盘 I/O 次数,需合理设计避免性能损耗。

2.1 索引基础

  • 存储结构:主要为 B+树(支持范围查询),哈希索引仅适用于等值查询(InnoDB 自适应)。

  • 分类:主键索引(聚簇索引,InnoDB 特有)、唯一索引、普通索引、联合索引、全文索引。

  • 核心区别:聚簇索引(数据与索引同存),非聚簇索引需回表查询,覆盖索引可避免回表。

2.2 索引优化技巧

  1. 选择区分度高的字段建索引,避免低区分度字段(如性别)。

  2. 联合索引遵循最左前缀原则,查询需匹配最左字段才生效。

  3. 避免索引失效:不使用函数操作、隐式类型转换、%开头模糊查询、not in 等。

  4. 主键用自增 id,减少页分裂,降低索引碎片。

6.MySQL 慢查询日志(实操)

慢查询日志用于定位执行缓慢的 SQL,是性能优化的重要工具。

3.1 核心配置

  • slow_query_log:开启慢查询开关;slow_query_log_file:日志文件路径。

  • long_query_time:慢 SQL 阈值(默认10秒);log_queries_not_using_indexes:记录无索引 SQL。

3.2 开启与分析

  • 开启方式:临时开启(session 级)、my.cnf 永久配置(需重启 MySQL)。

  • 分析工具:mysqldumpslow(简单分析)、pt-query-digest(详细分析)。

3.3 排查流程

开启慢日志 → 收集慢 SQL → explain 分析执行计划 → 优化索引/SQL → 压测验证。

  Slave_SQL_Running_State: Slave has read all relay log; waiting for more updates
       Master_Retry_Count: 86400
              Master_Bind:
  Last_IO_Error_Timestamp:
 Last_SQL_Error_Timestamp:
           Master_SSL_Crl:
       Master_SSL_Crlpath:
       Retrieved_Gtid_Set:
        Executed_Gtid_Set:
            Auto_Position: 0
     Replicate_Rewrite_DB:
             Channel_Name:
       Master_TLS_Version:

1 row in set (0.00 sec)

ERROR:
No query specified


# 4.MySQL 事务详解(ACID 四大特性)

事务是一组不可分割的 SQL 操作集合,核心是 ACID 四大特性,保障数据可靠性。

## 1.1 事务四大特性(ACID)

##### (1)原子性(Atomicity)

事务不可分割,要么全部执行成功提交,要么全部失败回滚,依赖 undo log 实现回滚。

##### (2)一致性(Consistency)

事务执行前后,数据库数据完整性约束不被破坏,是事务的最终目标。

##### (3)隔离性(Isolation)

多事务并发执行时互不干扰,MySQL 通过隔离级别平衡隔离性与并发性能,解决脏读、不可重复读、幻读问题。

4种隔离级别(从低到高):读未提交、读已提交(RC)、可重复读(RR,MySQL 默认)、串行化。

##### (4)持久性(Durability)

事务提交后,修改永久保存,即使 MySQL 崩溃也不会丢失,依赖 redo log 实现。

## 1.2 核心补充

InnoDB 依赖 MVCC(多版本并发控制)、read view 实现隔离性,通过锁机制解决写-写并发冲突;事务相关日志(redo log、undo log、binlog)各司其职,保障事务正常运行。

# 5.MySQL 索引核心原理与优化

索引是提升查询性能的核心,本质是 B+树数据结构,减少磁盘 I/O 次数,需合理设计避免性能损耗。

## 2.1 索引基础

- 存储结构:主要为 B+树(支持范围查询),哈希索引仅适用于等值查询(InnoDB 自适应)。

- 分类:主键索引(聚簇索引,InnoDB 特有)、唯一索引、普通索引、联合索引、全文索引。

- 核心区别:聚簇索引(数据与索引同存),非聚簇索引需回表查询,覆盖索引可避免回表。

## 2.2 索引优化技巧

1. 选择区分度高的字段建索引,避免低区分度字段(如性别)。

2. 联合索引遵循最左前缀原则,查询需匹配最左字段才生效。

3. 避免索引失效:不使用函数操作、隐式类型转换、%开头模糊查询、not in 等。

4. 主键用自增 id,减少页分裂,降低索引碎片。

# 6.MySQL 慢查询日志(实操)

慢查询日志用于定位执行缓慢的 SQL,是性能优化的重要工具。

## 3.1 核心配置

- slow_query_log:开启慢查询开关;slow_query_log_file:日志文件路径。

- long_query_time:慢 SQL 阈值(默认10秒);log_queries_not_using_indexes:记录无索引 SQL。

## 3.2 开启与分析

- 开启方式:临时开启(session 级)、my.cnf 永久配置(需重启 MySQL)。

- 分析工具:mysqldumpslow(简单分析)、pt-query-digest(详细分析)。

## 3.3 排查流程

开启慢日志 → 收集慢 SQL → explain 分析执行计划 → 优化索引/SQL → 压测验证。









Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐