本文主要是介绍掌握MySQL就差这一个——超详细讲解Mysql集群技术(包含主从复制,半同步模式,组复制,MHA),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一 Mysql 在服务器中的部署方法
在企业中 90% 的服务器操作系统均为 Linux
在企业中对于 Mysql 的安装通常用源码编译的方式来进行
官网: http://www.mysql.com
1.1 在Linux下部署mysql
1 安装依赖性:
[root@mysql_node1 ~]# yum install cmake gcc-c++ openssl-devel ncurses-devel.x86_64 -y
[root@mysql_node1 ~]# yum install libtirpc-devel-0.2.4-0.16.el7.x86_64.rpm -y #这个包可以取网站找2 下载并解压源码包
[root@mysql_node1 ~]# tar zxf mysql-boost-5.7.44.tar.gz
[root@mysql-node10 ~]# cd /root/mysql-5.7.443 源码编译安装mysql
[root@mysql_node1 mysql-5.7.44]# cmake \
-DCMAKE_INSTALL_PREFIX=/usr/local/mysql \ #指定安装路径
-DMYSQL_DATADIR=/data/mysql \ #指定数据目录
-DMYSQL_UNIX_ADDR=/data/mysql/mysql.sock \ #指定套接字文件
-DWITH_INNOBASE_STORAGE_ENGINE=1 \ #指定启用INNODB存储引擎,默认用myisam
-DWITH_EXTRA_CHARSETS=all \ #扩展字符集
-DDEFAULT_CHARSET=utf8mb4 \ #指定默认字符集
-DDEFAULT_COLLATION=utf8mb4_unicode_ci \ #指定默认校验字符集
-DWITH_BOOST=/root/mysql-5.7.44/boost/boost_1_59_0/ #指定c++库依赖[root@mysql_node1 mysql-5.7.44]# make -j2 #-j2 表示有几个核心就跑几个进程
[root@mysql_node1 mysql-5.7.44# make install#当cmake出错后如果想重新检测,删除 mysql-5.7.44 中 CMakeCache.txt即可4 部署mysql
#生成启动脚本
[root@mysql_node1 ~]# dnf install initscripts-10.11.6-1.el9.x86_64 -y
[root@mysql_node1 ~]# cd /usr/local/mysql/support-files/
[root@node1_node1 support-files]# cp mysql.server /etc/init.d/mysqld#修改环境变量
[root@node1_node1 ~]# vim ~/.bash_profile
export PATH=$PATH:/usr/local/mysql/bin
[root@node1_node1 ~]# source ~/.bash_profile#生成数据目录
[root@mysql_node1 ~]# useradd -s /sbin/nologin -M mysql
[root@mysql_node1 ~]# mkdir -p /data/mysql
[root@mysql_node1 ~]# chown mysql:mysql /data/mysql/#修改配置文件
[root@mysql_node1 ~]# vim /etc/my.cnf
[mysqld]
datadir=/data/mysql #指定数据目录
socket=/data/mysql/mysql.sock #指定套接字
symbolic-links=0 #数据只能存放到数据目录中,禁止链接到数据目录#数据库初始化建立mysql基本数据
[root@mysql_node1 ~]# mysqld --initialize --user=mysql #记住密码,后面登录用
[root@mysql_node1 ~]# /etc/init.d/mysqld start
[root@mysql_node1 ~]# chkconfig mysqld on#数据库安全初始化
[root@node1_node1 ~]# mysql_secure_installation #前两个选no,后面全部选yes[root@mysql_node1 ~]# mysql -uroot -p123
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
#如果出现这种情况,可以在/etc/my.cnf再添加两行
[root@mysql_node1 ~]# vim /etc/my.cnf
[client] #如果你在/etc/my.cnf中更改了socket路径,记得在mysql客户端命令中也使用正确的socket路径
socket=/data/mysql/mysql.sock
[root@mysql_node1 ~]# /etc/init.d/mysqld restart[root@mysql_node1 ~]# mysql -uroot -p123
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.44-log Source distributionCopyright (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)]> #需要三个机子,所以另外两个node2和node3也要安装mysql作为salve端,node1作为master端
[root@mysql_node2 ~]# useradd -s /sbin/nologin -M mysql
[root@mysql_node2 ~]# mkdir -p /data/mysql
[root@mysql_node2 ~]# chown mysql:mysql /data/mysql/[root@mysql_node1 ~]# rsync -al -r /usr/local/mysql root@172.25.254.
20:/usr/local/[root@mysql_node2 ~]# vim /etc/my.cnf
[mysqld]
datadir=/data/mysql
socket=/data/mysql/mysql.sock
symbolic-links=0a[client]
socket=/data/mysql/mysql.sock[root@node1_node2 ~]# vim ~/.bash_profile
export PATH=$PATH:/usr/local/mysql/bin
[root@node1_node2 ~]# source ~/.bash_profile
[root@mysql_node2 ~]# cp /usr/local/mysql/support-files/mysql.server /etc/init.d/mysqld
[root@mysql_node2 ~]# mysqld --initialize --user=mysql
[root@mysql_node2 ~]# /etc/init.d/mysqld start
[root@mysql_node2 ~]# mysql_secure_installation
[root@mysql_node2 ~]# mysql -uroot -p123
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MySQL connection id is 5
Server version: 5.7.44 Source distributionCopyright (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)]>#node3和node2一样做就ok了
二 mysql的组从复制
2.1 配置mastesr
[root@mysql_node1 ~]# vim /etc/my.cnf
[mysqld]
datadir=/data/mysql
socket=/data/mysql/mysql.sock
symbolic-links=0
log-bin=mysql-bin
server-id=1[client]
socket=/data/mysql/mysql.sock[root@mysql_node1 ~]# /etc/init.d/mysqld restart#进入数据库配置用户权限
[root@mysql_node1 ~]# mysql -p123
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.7.44 Source distributionCopyright (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)]> create user 'repl'@'%' identified by 'liu'; #生成专门用来做复制的用户,此用户是用于slave端做认证用
Query OK, 0 rows affected (0.00 sec)MySQL [(none)]> grant replication slave on *.* to repl@'%'; #对这个用户进行授权
Query OK, 0 rows affected (0.00 sec)MySQL [(none)]> show master status; #查看master的状态
+------------------+----------+--------------+------------------+-------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+------------------+----------+--------------+------------------+-------------------+
| mysql-bin.000001 | 154 | | | |
+------------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)[root@mysql_node1 ~]# cd /data/mysql/
[root@mysql_node1 mysql]# mysqlbinlog mysql-bin.000001 #查看二进制日志
2.2 配置salve
[root@mysql_node2 ~]# vim /etc/my.cnf
[mysqld]
datadir=/data/mysql
socket=/data/mysql/mysql.sock
symbolic-links=0
server-id=2[client]
socket=/data/mysql/mysql.sock[root@mysql_node2 ~]# /etc/init.d/mysqld restart
Shutting down MySQL.. SUCCESS!
Starting MySQL. SUCCESS! [root@mysql_node2 ~]# mysql -p123
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.44 Source distributionCopyright (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)]> CHANGE MASTER TO MASTER_HOST='172.25.254.10',MASTER_USER='repl',MASTER_PASSWORD='liu',MASTER_LOG_FILE='mysql-bin.000001',MASTER_LOG_POS=154;
Query OK, 0 rows affected, 2 warnings (0.02 sec)MySQL [(none)]> start slave;
Query OK, 0 rows affected (0.00 sec)MySQL [(none)]> show slave status\G;
*************************** 1. row ***************************Slave_IO_State: Waiting for master to send eventMaster_Host: 172.25.254.10Master_User: replMaster_Port: 3306Connect_Retry: 60Master_Log_File: mysql-bin.000001Read_Master_Log_Pos: 154Relay_Log_File: mysql_node2-relay-bin.000002Relay_Log_Pos: 320Relay_Master_Log_File: mysql-bin.000001Slave_IO_Running: YesSlave_SQL_Running: YesReplicate_Do_DB: Replicate_Ignore_DB: Replicate_Do_Table: Replicate_Ignore_Table: Replicate_Wild_Do_Table: Replicate_Wild_Ignore_Table: Last_Errno: 0Last_Error: Skip_Counter: 0Exec_Master_Log_Pos: 154Relay_Log_Space: 533Until_Condition: NoneUntil_Log_File: Until_Log_Pos: 0Master_SSL_Allowed: NoMaster_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: NoLast_IO_Errno: 0Last_IO_Error: Last_SQL_Errno: 0Last_SQL_Error: Replicate_Ignore_Server_Ids: Master_Server_Id: 1Master_UUID: 739a505f-6479-11ef-9553-000c299a8c10Master_Info_File: /data/mysql/master.infoSQL_Delay: 0SQL_Remaining_Delay: NULLSlave_SQL_Running_State: Slave has read all relay log; waiting for more updatesMaster_Retry_Count: 86400Master_Bind: Last_IO_Error_Timestamp: Last_SQL_Error_Timestamp: Master_SSL_Crl: Master_SSL_Crlpath: Retrieved_Gtid_Set: Executed_Gtid_Set: Auto_Position: 0Replicate_Rewrite_DB: Channel_Name: Master_TLS_Version:
1 row in set (0.00 sec)ERROR: No query specified
测试:
#master端
[root@mysql_node1 ~]# mysql -p123
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.7.44-log Source distributionCopyright (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)]> CREATE DATABASE liu;
Query OK, 1 row affected (0.00 sec)MySQL [(none)]> CREATE TABLE liu.userlist (-> username varchar(20) not null,-> password varchar(50) not null-> );
Query OK, 0 rows affected (0.02 sec)MySQL [(none)]> INSERT INTO liu.userlist VALUE ('user1','123');
Query OK, 1 row affected (0.02 sec)MySQL [(none)]> SELECT * FROM liu.userlist;
+----------+----------+
| username | password |
+----------+----------+
| user1 | 123 |
+----------+----------+
1 row in set (0.00 sec)#slave端中查看数据是否有同步过来[root@mysql_node2 ~]# mysql -p123
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MySQL connection id is 5
Server version: 5.7.44 Source distributionCopyright (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)]> SELECT * FROM liu.userlist;
+----------+----------+
| username | password |
+----------+----------+
| user1 | 123 |
+----------+----------+
1 row in set (0.00 sec)MySQL [(none)]>
2.3 当有数据时添加slave2
#完成基础配置
[root@mysql_node3 ~]# vim /etc/my.cnf
[mysqld]
datadir=/data/mysql
socket=/data/mysql/mysql.sock
symbolic-links=0
server-id=3[client]
socket=/data/mysql/mysql.sock[root@mysql_node3 ~]# /etc/init.d/mysqld restart#从master节点备份数据
[root@mysql_node1 ~]# mysqldump -uroot -p123 liu > liu.sql
[root@mysql_node1 ~]# scp liu.sql root@172.25.254.30:/mnt/
root@172.25.254.30's password:
liu.sql 100% 1953 828.2KB/s 00:00 #利用master节点中备份出来的lee.sql在slave2中拉平数据
[root@mysql_node3 ~]# ls /mnt/
liu.sql
[root@mysql_node3 ~]# mysql -uroot -p123 -e "create database liu;"
[root@mysql_node3 ~]# mysql -p123 liu < /mnt/liu.sql
[root@mysql_node3 ~]# mysql -p123 -e "select * from liu.userlist;"
+----------+----------+
| username | password |
+----------+----------+
| user1 | 123 |
+----------+----------+#配置slave2的slave功能#在master中查询日志pos
[root@mysql_node1 ~]# mysql -p123 -e "show master status;"
+------------------+----------+--------------+------------------+-------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+------------------+----------+--------------+------------------+-------------------+
| mysql-bin.000001 | 799 | | | |
+------------------+----------+--------------+------------------+-------------------+[root@mysql_node3 ~]# mysql -p123
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MySQL connection id is 6
Server version: 5.7.44 Source distributionCopyright (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)]> CHANGE MASTER TO MASTER_HOST='172.25.254.10', MASTER_USER='repl',MASTER_PASSWORD='liu', MASTER_LOG_FILE='mysql-bin.000001', MASTER_LOG_POS=799;
Query OK, 0 rows affected, 2 warnings (0.02 sec)MySQL [(none)]> start slave;
Query OK, 0 rows affected (0.00 sec)MySQL [(none)]> show slave status;
*************************** 1. row ***************************Slave_IO_State: Waiting for master to send eventMaster_Host: 172.25.254.10Master_User: replMaster_Port: 3306Connect_Retry: 60Master_Log_File: mysql-bin.000001Read_Master_Log_Pos: 799Relay_Log_File: mysql_node3-relay-bin.000002Relay_Log_Pos: 320Relay_Master_Log_File: mysql-bin.000001Slave_IO_Running: YesSlave_SQL_Running: YesReplicate_Do_DB: Replicate_Ignore_DB: Replicate_Do_Table: Replicate_Ignore_Table: Replicate_Wild_Do_Table: Replicate_Wild_Ignore_Table: Last_Errno: 0Last_Error: Skip_Counter: 0Exec_Master_Log_Pos: 799Relay_Log_Space: 533Until_Condition: NoneUntil_Log_File: Until_Log_Pos: 0Master_SSL_Allowed: NoMaster_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: NoLast_IO_Errno: 0Last_IO_Error: Last_SQL_Errno: 0Last_SQL_Error: Replicate_Ignore_Server_Ids: Master_Server_Id: 1Master_UUID: 739a505f-6479-11ef-9553-000c299a8c10Master_Info_File: /data/mysql/master.infoSQL_Delay: 0SQL_Remaining_Delay: NULLSlave_SQL_Running_State: Slave has read all relay log; waiting for more updatesMaster_Retry_Count: 86400Master_Bind: Last_IO_Error_Timestamp: Last_SQL_Error_Timestamp: Master_SSL_Crl: Master_SSL_Crlpath: Retrieved_Gtid_Set: Executed_Gtid_Set: Auto_Position: 0Replicate_Rewrite_DB: Channel_Name: Master_TLS_Version:
1 row in set (0.00 sec)ERROR: No query specified
继续测试:
[root@mysql_node1 ~]# mysql -p123MySQL [(none)]> INSERT INTO liu.userlist VALUES('user2','123');
Query OK, 1 row affected (0.01 sec)MySQL [(none)]> select * from liu.userlist;
+----------+----------+
| username | password |
+----------+----------+
| user1 | 123 |
| user2 | 123 |
+----------+----------+
2 rows in set (0.00 sec)[root@mysql_node3 ~]# mysql -p123MySQL [(none)]> select * from liu.userlist;
+----------+----------+
| username | password |
+----------+----------+
| user1 | 123 |
| user2 | 123 |
+----------+----------+
2 rows in set (0.00 sec)
2.4 延迟复制
延迟复制时用来控制 sql 线程的,和 i/o 线程无关这个延迟复制不是 i/o 线程过段时间来复制, i/o 是正常工作的是日志已经保存在 slave 端了,那个 sql 要等多久进行回放当 master 端误操作,可以在 slave 端进行数据备份
#在slave端
[root@mysql_node2 ~]# mysql -p123MySQL [(none)]> STOP SLAVE SQL_THREAD;
Query OK, 0 rows affected (0.01 sec)MySQL [(none)]> CHANGE MASTER TO MASTER_DELAY=30;
Query OK, 0 rows affected (0.00 sec)MySQL [(none)]> START SLAVE SQL_THREAD;
Query OK, 0 rows affected (0.00 sec)MySQL [(none)]> SHOW SLAVE STATUS\G;
在 master 中写入数据后过了延迟时间30秒后才能被查询到
2.5 慢查询日志
- 慢查询,顾名思义,执行很慢的查询
- 当执行SQL超过long_query_time参数设定的时间阈值(默认10s)时,就被认为是慢查询,这个 SQL语句就是需要优化的
- 慢查询被记录在慢查询日志里
- 慢查询日志默认是不开启的
- 如果需要优化SQL语句,就可以开启这个功能,它可以让你很容易地知道哪些语句是需要优化的。
[root@mysql_node1 ~]# mysql -p123MySQL [(none)]> SHOW variables like "slow%";
+---------------------+----------------------------------+
| Variable_name | Value |
+---------------------+----------------------------------+
| slow_launch_time | 2 |
| slow_query_log | OFF |
| slow_query_log_file | /data/mysql/mysql_node1-slow.log |
+---------------------+----------------------------------+
3 rows in set (0.01 sec)MySQL [(none)]> SET GLOBAL slow_query_log=ON; #开启慢查询日志
Query OK, 0 rows affected (0.01 sec)MySQL [(none)]> SET long_query_time=4;
Query OK, 0 rows affected (0.00 sec)MySQL [(none)]> SHOW VARIABLES like "long%";
+-----------------+----------+
| Variable_name | Value |
+-----------------+----------+
| long_query_time | 4.000000 |
+-----------------+----------+
1 row in set (0.00 sec)MySQL [(none)]> SHOW VARIABLES like "slow%";
+---------------------+----------------------------------+
| Variable_name | Value |
+---------------------+----------------------------------+
| slow_launch_time | 2 |
| slow_query_log | ON | #慢查询日志开启
| slow_query_log_file | /data/mysql/mysql_node1-slow.log |
+---------------------+----------------------------------+
3 rows in set (0.00 sec)MySQL [(none)]> select sleep (10);[root@mysql_node1 ~]# cat /data/mysql/mysql_node1-slow.log #慢查询日志
/usr/local/mysql/bin/mysqld, Version: 5.7.44-log (Source distribution). started with:
Tcp port: 3306 Unix socket: /data/mysql/mysql.sock
Time Id Command Argument
# Time: 2024-08-29T12:45:30.792699Z
# User@Host: root[root] @ localhost [] Id: 10
# Query_time: 10.000788 Lock_time: 0.000000 Rows_sent: 1 Rows_examined: 0
SET timestamp=1724935530;
select sleep (10);
# Time: 2024-08-29T12:46:31.747220Z
# User@Host: root[root] @ localhost [] Id: 11
# Query_time: 10.001382 Lock_time: 0.000000 Rows_sent: 1 Rows_examined: 0
SET timestamp=1724935591;
select sleep (10);
2.6 mysql的并行复制
默认情况下 slave 中使用的是 sql 单线程回放
在 master 中时多用户读写,如果使用 sql 单线程回放那么会造成组从延迟严重
开启 MySQL 的多线程回放可以解决上述问题
在slaves中设定
[root@mysql_node2 ~]# vim /etc/my.cnf[mysqld]
datadir=/data/mysql
socket=/data/mysql/mysql.sock
symbolic-links=0
server-id=2
gtid_mode=ON
enforce-gtid-consistency=ON
slave-parallel-type=LOGICAL_CLOCK #基于组提交
slave-parallel-workers=16 #开启线程数量
master_info_repository=TABLE #master信息在表中记录,默认记录在/data/mysql//master.info
relay_log_info_repository=TABLE #回放日志信息在表中记录,默认记录在/data/mysql/relay-log.info
relay_log_recovery=ON #日志回放恢复功能开启[client]
socket=/data/mysql/mysql.sock[root@mysql_node2 ~]# /etc/init.d/mysqld restart[root@mysql_node2 ~]# mysql -p123 -e "show processlist;"
+----+-------------+-----------+------+---------+------+--------------------------------------------------------+------------------+
| Id | User | Host | db | Command | Time | State | Info |
+----+-------------+-----------+------+---------+------+--------------------------------------------------------+------------------+
| 2 | system user | | NULL | Connect | 28 | Slave has read all relay log; waiting for more updates | NULL |
| 3 | system user | | NULL | Connect | 29 | Waiting for an event from Coordinator | NULL |
| 4 | system user | | NULL | Connect | 29 | Waiting for an event from Coordinator | NULL |
| 5 | system user | | NULL | Connect | 29 | Waiting for an event from Coordinator | NULL |
| 6 | system user | | NULL | Connect | 29 | Waiting for an event from Coordinator | NULL |
| 7 | system user | | NULL | Connect | 29 | Waiting for an event from Coordinator | NULL |
| 8 | system user | | NULL | Connect | 29 | Waiting for an event from Coordinator | NULL |
| 9 | system user | | NULL | Connect | 29 | Waiting for an event from Coordinator | NULL |
| 10 | system user | | NULL | Connect | 29 | Waiting for an event from Coordinator | NULL |
| 11 | system user | | NULL | Connect | 29 | Waiting for an event from Coordinator | NULL |
| 12 | system user | | NULL | Connect | 29 | Waiting for an event from Coordinator | NULL |
| 13 | system user | | NULL | Connect | 29 | Waiting for an event from Coordinator | NULL |
| 15 | system user | | NULL | Connect | 29 | Waiting for an event from Coordinator | NULL |
| 16 | system user | | NULL | Connect | 29 | Waiting for an event from Coordinator | NULL |
| 17 | system user | | NULL | Connect | 29 | Waiting for an event from Coordinator | NULL |
| 18 | system user | | NULL | Connect | 28 | Waiting for an event from Coordinator | NULL |
| 19 | system user | | NULL | Connect | 28 | Waiting for an event from Coordinator | NULL |
| 20 | root | localhost | NULL | Query | 0 | starting | show processlist |
+----+-------------+-----------+------+---------+------+--------------------------------------------------------+------------------+
此时sql线程转化为协调线程,16个worker负责处理sql协调线程发送过来的处理请求
MySQL 组提交( Group commit )是一个性能优化特性,它允许在一个事务日志同步操作中将多个 事务的日志记录一起写入。这样做可以减少磁盘I/O 的次数,从而提高数据库的整体性能。
2.7 原理解析和架构缺陷
三个线程实际上主从同步的原理就是基于 binlog 进行数据同步的。在主从复制过程中,会基于 3 个线程来操作,一个主库线程,两个从库线程。
- 二进制日志转储线程(Binlog dump thread)是一个主库线程。当从库线程连接的时候, 主库可以 将二进制日志发送给从库,当主库读取事件(Event)的时候,会在 Binlog 上加锁,读取完成之 后,再将锁释放掉。
- 从库 I/O 线程会连接到主库,向主库发送请求更新 Binlog。这时从库的 I/O 线程就可以读取到主库 的二进制日志转储线程发送的 Binlog 更新部分,并且拷贝到本地的中继日志 (Relay log)。
- 从库 SQL 线程会读取从库中的中继日志,并且执行日志中的事件,将从库中的数据与主库保持同 步。
复制三步骤步骤 1 : Master 将写操作记录到二进制日志( binlog )。步骤 2 : Slave 将 Master 的 binary log events 拷贝到它的中继日志( relay log );步骤 3 : Slave 重做中继日志中的事件,将改变应用到自己的数据库中。 MySQL 复制是异步的且串行化的,而且重启后从接入点开始复制。具体操作1.slaves 端中设置了 master 端的 ip ,用户,日志,和日志的 Position ,通过这些信息取得 master 的认证及信息2.master 端在设定好 binlog 启动后会开启 binlog dump 的线程3.master 端的 binlog dump 把二进制的更新发送到 slave 端的4.slave 端开启两个线程,一个是 I/O 线程,一个是 sql 线程,
- i/o线程用于接收master端的二进制日志,此线程会在本地打开relaylog中继日志,并且保存到本地 磁盘
- sql线程读取本地relog中继日志进行回放
5. 什么时候我们需要多个 slave ?当读取的而操作远远高与写操作时。我们采用一主多从架构数据库外层接入负载均衡层并搭配高可用机制架构缺陷主从架构采用的是异步机制master 更新完成后直接发送二进制日志到 slave ,但是 slaves 是否真正保存了数据 master 端不会检测master 端直接保存二进制日志到磁盘当 master 端到 slave 端的网络出现问题时或者 master 端直接挂掉,二进制日志可能根本没有到达 slavemaster 出现问题 slave 端接管 master ,这个过程中数据就丢失了这样的问题出现就无法达到数据的强一致性,零数据丢失
三 半同步模式
3.1半同步模式原理
1. 用户线程写入完成后 master 中的 dump 会把日志推送到 slave 端2.slave 中的 io 线程接收后保存到 relaylog 中继日志3. 保存完成后 slave 向 master 端返回 ack4. 在未接受到 slave 的 ack 时 master 端时不做提交的,一直处于等待当收到 ack 后提交到存储引擎5. 在 5.6 版本中用到的时 after_commit 模式, after_commit 模式时先提交在等待 ack 返回后输出 ok
3.2 gtid模式
当为启用 gtid 时我们要考虑的问题在 master 端的写入时多用户读写,在 slave 端的复制时单线程日志回放,所以 slave 端一定会延迟与master 端这种延迟在 slave 端的延迟可能会不一致,当 master 挂掉后 slave 接管,一般会挑选一个和 master 延迟日志最接近的充当新的master那么为接管 master 的主机继续充当 slave 角色并会指向到新的 master 上,作为其 slave这时候按照之前的配置我们需要知道新的 master 上的 pos 的 id ,但是我们无法确定新的 master 和 slave 之间差多少当激活 GITD 之后当 master 出现问题后, slave2 和 master 的数据最接近,会被作为新的 masterslave1 指向新的 master ,但是他不会去检测新的 master 的 pos id ,只需要继续读取自己 gtid_next 即可
设置 gtid
#在master端和slave端开启gtid模式
[root@mysql_node1 ~]# vim /etc/my.cnf
[mysqld]
datadir=/data/mysql
socket=/data/mysql/mysql.sock
symbolic-links=0
log-bin=mysql-bin
server-id=1
gtid_mode=ON
enforce-gtid-consistency=ON[client]
socket=/data/mysql/mysql.sock
[root@mysql_node1 ~]# /etc/init.d/mysqld restart[root@mysql_node2 ~]# vim /etc/my.cnf
[mysqld]
datadir=/data/mysql
socket=/data/mysql/mysql.sock
symbolic-links=0
server-id=2
log-bin=mysql-bin
gtid_mode=ON
enforce-gtid-consistency=ON[client]
socket=/data/mysql/mysql.sock
[root@mysql_node2 ~]# /etc/init.d/mysqld restart[root@mysql_node3 ~]# vim /etc/my.cnf
[mysqld]
datadir=/data/mysql
socket=/data/mysql/mysql.sock
symbolic-links=0
server-id=3
log-bin=mysql-bin
gtid_mode=ON
enforce-gtid-consistency=ON[client]
socket=/data/mysql/mysql.sock
[root@mysql_node3 ~]# /etc/init.d/mysqld restart#停止slave端
[root@mysql_node2 ~]# mysql -p123MySQL [(none)]> stop slave;
Query OK, 0 rows affected (0.00 sec)[root@mysql_node3 ~]# mysql -p123MySQL [(none)]> stop slave;
Query OK, 0 rows affected (0.00 sec)#开启slave端的gtid #slave1和slave2都要开
MySQL [(none)]> CHANGE MASTER TO MASTER_HOST='172.25.254.10', MASTER_USER='repl',MASTER_PASSWORD='liu', MASTER_AUTO_POSITION=1;
Query OK, 0 rows affected, 2 warnings (0.02 sec)MySQL [(none)]> start slave;
Query OK, 0 rows affected (0.00 sec)MySQL [(none)]> show slave status\G;
*************************** 1. row ***************************Slave_IO_State: Waiting for master to send eventMaster_Host: 172.25.254.10Master_User: replMaster_Port: 3306Connect_Retry: 60Master_Log_File: mysql-bin.000002Read_Master_Log_Pos: 154Relay_Log_File: mysql_node2-relay-bin.000002Relay_Log_Pos: 367Relay_Master_Log_File: mysql-bin.000002Slave_IO_Running: YesSlave_SQL_Running: YesReplicate_Do_DB: Replicate_Ignore_DB: Replicate_Do_Table: Replicate_Ignore_Table: Replicate_Wild_Do_Table: Replicate_Wild_Ignore_Table: Last_Errno: 0Last_Error: Skip_Counter: 0Exec_Master_Log_Pos: 154Relay_Log_Space: 580Until_Condition: NoneUntil_Log_File: Until_Log_Pos: 0Master_SSL_Allowed: NoMaster_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: NoLast_IO_Errno: 0Last_IO_Error: Last_SQL_Errno: 0Last_SQL_Error: Replicate_Ignore_Server_Ids: Master_Server_Id: 1Master_UUID: 739a505f-6479-11ef-9553-000c299a8c10Master_Info_File: /data/mysql/master.infoSQL_Delay: 30SQL_Remaining_Delay: NULLSlave_SQL_Running_State: Slave has read all relay log; waiting for more updatesMaster_Retry_Count: 86400Master_Bind: Last_IO_Error_Timestamp: Last_SQL_Error_Timestamp: Master_SSL_Crl: Master_SSL_Crlpath: Retrieved_Gtid_Set: Executed_Gtid_Set: Auto_Position: 1 #功能开启Replicate_Rewrite_DB: Channel_Name: Master_TLS_Version:
1 row in set (0.00 sec)ERROR: No query specified
3.3.启用半同步模式
在 master 端配置启用半同步模式
[root@mysql_node1 ~]# vim /etc/my.cnf
[mysqld]
datadir=/data/mysql
socket=/data/mysql/mysql.sock
symbolic-links=0
log-bin=mysql-bin
server-id=1
gtid_mode=ON
enforce-gtid-consistency=ON
rpl_semi_sync_master_enabled=1[client]
socket=/data/mysql/mysql.sock
#先不重启mysql,会报错[root@mysql_node1 ~]# mysql -p123MySQL [(none)]> INSTALL PLUGIN rpl_semi_sync_master SONAME 'semisync_master.so'; #安装半同步插件
Query OK, 0 rows affected (0.01 sec)MySQL [(none)]> SELECT PLUGIN_NAME, PLUGIN_STATUS -> FROM INFORMATION_SCHEMA.PLUGINS-> WHERE PLUGIN_NAME LIKE '%semi%'; #查看插件情况
+----------------------+---------------+
| PLUGIN_NAME | PLUGIN_STATUS |
+----------------------+---------------+
| rpl_semi_sync_master | ACTIVE |
+----------------------+---------------+
1 row in set (0.00 sec)MySQL [(none)]> SET GLOBAL rpl_semi_sync_master_enabled = 1; #打开半同步功能
Query OK, 0 rows affected (0.00 sec)MySQL [(none)]> SHOW VARIABLES LIKE 'rpl_semi_sync%'; #查看半同步功能状态
+-------------------------------------------+------------+
| Variable_name | Value |
+-------------------------------------------+------------+
| rpl_semi_sync_master_enabled | ON |
| rpl_semi_sync_master_timeout | 10000 |
| rpl_semi_sync_master_trace_level | 32 |
| rpl_semi_sync_master_wait_for_slave_count | 1 |
| rpl_semi_sync_master_wait_no_slave | ON |
| rpl_semi_sync_master_wait_point | AFTER_SYNC |
+-------------------------------------------+------------+
6 rows in set (0.01 sec)MySQL [(none)]> SHOW STATUS LIKE 'Rpl_semi_sync%';
+--------------------------------------------+-------+
| Variable_name | Value |
+--------------------------------------------+-------+
| Rpl_semi_sync_master_clients | 0 |
| Rpl_semi_sync_master_net_avg_wait_time | 0 |
| Rpl_semi_sync_master_net_wait_time | 0 |
| Rpl_semi_sync_master_net_waits | 0 |
| Rpl_semi_sync_master_no_times | 0 |
| Rpl_semi_sync_master_no_tx | 0 |
| Rpl_semi_sync_master_status | ON |
| Rpl_semi_sync_master_timefunc_failures | 0 |
| Rpl_semi_sync_master_tx_avg_wait_time | 0 |
| Rpl_semi_sync_master_tx_wait_time | 0 |
| Rpl_semi_sync_master_tx_waits | 0 |
| Rpl_semi_sync_master_wait_pos_backtraverse | 0 |
| Rpl_semi_sync_master_wait_sessions | 0 |
| Rpl_semi_sync_master_yes_tx | 0 |
+--------------------------------------------+-------+
14 rows in set (0.00 sec)MySQL [(none)]> show plugins;
在 slave 端开启半同步功能
[root@mysql_node2 ~]# vim /etc/my.cnf
[mysqld]
datadir=/data/mysql
socket=/data/mysql/mysql.sock
symbolic-links=0
server-id=2
log-bin=mysql-bin
gtid_mode=ON
enforce-gtid-consistency=ON
rpl_semi_sync_slave_enabled=1 #开启半同步功能[client]
socket=/data/mysql/mysql.sock[root@mysql_node2 ~]# mysql -p123MySQL [(none)]> INSTALL PLUGIN rpl_semi_sync_slave SONAME 'semisync_slave.so';
Query OK, 0 rows affected (0.00 sec)MySQL [(none)]> SET GLOBAL rpl_semi_sync_slave_enabled =1;
Query OK, 0 rows affected (0.00 sec)MySQL [(none)]> STOP SLAVE IO_THREAD; #重启io线程,半同步才能生效
Query OK, 0 rows affected (0.01 sec)MySQL [(none)]> START SLAVE IO_THREAD;
Query OK, 0 rows affected (0.00 sec)MySQL [(none)]> SHOW VARIABLES LIKE 'rpl_semi_sync%';
+---------------------------------+-------+
| Variable_name | Value |
+---------------------------------+-------+
| rpl_semi_sync_slave_enabled | ON |
| rpl_semi_sync_slave_trace_level | 32 |
+---------------------------------+-------+
2 rows in set (0.01 sec)MySQL [(none)]> SHOW STATUS LIKE 'Rpl_semi_sync%';
+----------------------------+-------+
| Variable_name | Value |
+----------------------------+-------+
| Rpl_semi_sync_slave_status | ON |
+----------------------------+-------+
1 row in set (0.00 sec)[root@mysql_node3 ~]# vim /etc/my.cnf
[mysqld]
datadir=/data/mysql
socket=/data/mysql/mysql.sock
symbolic-links=0
server-id=3
log-bin=mysql-bin
gtid_mode=ON
enforce-gtid-consistency=ON
rpl_semi_sync_slave_enabled=1[client]
socket=/data/mysql/mysql.sock[root@mysql_node3 ~]# mysql -p123MySQL [(none)]> INSTALL PLUGIN rpl_semi_sync_slave SONAME 'semisync_slave.so';
Query OK, 0 rows affected (0.01 sec)MySQL [(none)]> SET GLOBAL rpl_semi_sync_slave_enabled =1;
Query OK, 0 rows affected (0.00 sec)MySQL [(none)]> STOP SLAVE IO_THREAD;
Query OK, 0 rows affected (0.00 sec)MySQL [(none)]> START SLAVE IO_THREAD;
Query OK, 0 rows affected (0.00 sec)MySQL [(none)]> SHOW VARIABLES LIKE 'rpl_semi_sync%';
+---------------------------------+-------+
| Variable_name | Value |
+---------------------------------+-------+
| rpl_semi_sync_slave_enabled | ON |
| rpl_semi_sync_slave_trace_level | 32 |
+---------------------------------+-------+
2 rows in set (0.01 sec)
3.4.测试
在 master 端写入数据
[root@mysql_node1 ~]# mysql -p123MySQL [(none)]> insert into liu.userlist values ('user3','123');
Query OK, 1 row affected (0.05 sec)MySQL [(none)]> SHOW STATUS LIKE 'Rpl_semi_sync%';
+--------------------------------------------+-------+
| Variable_name | Value |
+--------------------------------------------+-------+
| Rpl_semi_sync_master_clients | 2 |
| Rpl_semi_sync_master_net_avg_wait_time | 0 |
| Rpl_semi_sync_master_net_wait_time | 0 |
| Rpl_semi_sync_master_net_waits | 2 |
| Rpl_semi_sync_master_no_times | 0 |
| Rpl_semi_sync_master_no_tx | 0 |
| Rpl_semi_sync_master_status | ON |
| Rpl_semi_sync_master_timefunc_failures | 0 |
| Rpl_semi_sync_master_tx_avg_wait_time | 1363 |
| Rpl_semi_sync_master_tx_wait_time | 1363 |
| Rpl_semi_sync_master_tx_waits | 1 |
| Rpl_semi_sync_master_wait_pos_backtraverse | 0 |
| Rpl_semi_sync_master_wait_sessions | 0 |
| Rpl_semi_sync_master_yes_tx | 1 |
+--------------------------------------------+-------+
14 rows in set (0.01 sec)
模拟故障:
#在slave端
[root@mysql_node2 ~]# mysql -p123MySQL [(none)]> STOP SLAVE IO_THREAD;
Query OK, 0 rows affected (0.00 sec)[root@mysql_node3 ~]# mysql -p123MySQL [(none)]> STOP SLAVE IO_THREAD;
Query OK, 0 rows affected (0.00 sec)#在master端插入数据
MySQL [(none)]> insert into liu.userlist values ('user4','123');
Query OK, 1 row affected (10.00 sec) #10秒超时MySQL [(none)]> SHOW STATUS LIKE 'Rpl_semi_sync%';
+--------------------------------------------+-------+
| Variable_name | Value |
+--------------------------------------------+-------+
| Rpl_semi_sync_master_clients | 1 |
| Rpl_semi_sync_master_net_avg_wait_time | 0 |
| Rpl_semi_sync_master_net_wait_time | 0 |
| Rpl_semi_sync_master_net_waits | 3 |
| Rpl_semi_sync_master_no_times | 1 |
| Rpl_semi_sync_master_no_tx | 1 | #一笔数据为同步
| Rpl_semi_sync_master_status | OFF | #自动转为异步模式,当slave恢复
| Rpl_semi_sync_master_timefunc_failures | 0 | #会自动恢复
| Rpl_semi_sync_master_tx_avg_wait_time | 1363 |
| Rpl_semi_sync_master_tx_wait_time | 1363 |
| Rpl_semi_sync_master_tx_waits | 1 |
| Rpl_semi_sync_master_wait_pos_backtraverse | 0 |
| Rpl_semi_sync_master_wait_sessions | 0 |
| Rpl_semi_sync_master_yes_tx | 1 |
+--------------------------------------------+-------+
14 rows in set (0.01 sec)
四 mysql高可用之组复制 (MGR)
MySQL Group Replication( 简称 MGR ) 是 MySQL 官方于 2016 年 12 月推出的一个全新的高可用与高扩展的解决方案组复制是 MySQL 5.7.17 版本出现的新特性,它提供了高可用、高扩展、高可靠的 MySQL 集群服务MySQL 组复制分单主模式和多主模式,传统的 mysql 复制技术仅解决了数据同步的问题,MGR 对属于同一组的服务器自动进行协调。对于要提交的事务,组成员必须就全局事务序列中给定事务的顺序达成一致提交或回滚事务由每个服务器单独完成,但所有服务器都必须做出相同的决定如果存在网络分区,导致成员无法达成事先定义的分割策略,则在解决此问题之前系统不会继续进行,这是一种内置的自动裂脑保护机制MGR 由组通信系统 ( Group Communication System , GCS ) 协议支持该系统提供故障检测机制、组成员服务以及安全且有序的消息传递
4.1 组复制流程
首先我们将多个节点共同组成一个复制组,在执行读写( RW )事务的时候,需要通过一致性协议层(Consensus 层)的同意,也就是读写事务想要进行提交,必须要经过组里 “ 大多数人 ” (对应 Node 节点)的同意,大多数指的是同意的节点数量需要大于 (N/2+1 ),这样才可以进行提交,而不是原发起方一个说了算。而针对只读(RO )事务则不需要经过组内同意,直接 提交 即可注意:节点数量不能超过9台
4.2 组复制单主和多主模式
single-primary mode( 单写或单主模式 )
单写模式 group 内只有一台节点可写可读,其他节点只可以读。当主服务器失败时,会自动选择新的主服务器
multi-primary mode( 多写或多主模式 )
组内的所有机器都是 primary 节点,同时可以进行读写操作,并且数据是最终一致的。
4.3.实现mysql组复制
这篇关于掌握MySQL就差这一个——超详细讲解Mysql集群技术(包含主从复制,半同步模式,组复制,MHA)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!