主从简介
我们一般应用对数据库而言都是“读多写少”,也就说对数据库读取数据的压力比较大,有一个思路就是说采用数据库集群的方案,其中一个是主库,负责写入数据,我们称之为:写库;其它都是从库,负责读取数据,我们称之为:读库。
1.主从作用
- 实时灾备,用于故障切换
- 读写分离,提供查询服务
- 备份,避免影响业务
2.主从形式
- 一主一从(master主,slave从)
- 主主复制(两个都是主,也都是从,数据一样)
- 一主多从—扩展系统读取的性能,因为读是在从库读取的
- 多主一从—5.7开始支持
- 联级复制
3.主从复制原理
主从复制步骤:
- 主库将所有的写操作记录到binlog日志中并生成一个log dump线程,将binlog日志传给从库的I/O线程
- 从库生成两个线程,一个I/O线程,一个SQL线程
- I/O线程去请求主库的binlog,并将得到的binlog日志写到relay log(中继日志) 文件中
- SQL线程,会读取relay log文件中的日志,并解析成具体操作,来实现主从的操作一致,达到最终数据一致的目的
4.主从复制配置
主从复制配置步骤:
- 确保从数据库与主数据库里的数据一样
- 在主数据库里创建一个同步账号授权给从数据库使用
- 配置主数据库(修改配置文件)
- 配置从数据库(修改配置文件)
需求:
搭建两台MySQL
服务器,一台作为主服务器,一台作为从服务器,主服务器进行写操作,从服务器进行读操作
环境说明:
数据库角色 | IP | 应用与系统版本 | 有无数据 |
主数据库 | 192.168.152.134 [root@master ~] | centos8/redhat8 mysql-5.7 | 无数据 |
从数据库 | 192.168.152.135 [root@slave ~] | centos8/redhat8mysql-5.7 | 无数据 |
- MySQL安装,分别在主从两台服务器上安装
mysql-5.7
版本
//执行此操作请参考上一篇的实例部署
[root@master ~]# ls
anaconda-ks.cfg mysql.22
[root@master mysql.22]# ls
install.sh soft
[root@master mysql.22]# chmod +x install.sh
[root@master mysql.22]# bash install.sh
请输入您要创建的实例个数: 1
请输入您要为数据库设置的密码: 123456
正在初始化 3306 实例...
Starting MySQL.Logging to '/data/3306/master.err'.
SUCCESS!
[root@master ~]# mysql -uroot -p123456
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 3
Server version: 5.7.31 MySQL Community Server (GPL)
Copyright (c) 2000, 2020, 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>
- 在主数据库创建一个同步账户授权给从数据库使用
//创建同步账户名repl,授权给135主机同步,密码为repl123
mysql> grant replication slave on *.* to repl@192.168.152.135 identified by 'repl123';
Query OK, 0 rows affected, 1 warning (0.01 sec)
mysql> flush privileges; //刷新权限
Query OK, 0 rows affected (0.00 sec)
//在135从主机上登录134的授权账户repl
[root@slave ~]# mysql -urepl -prepl123 -h192.168.152.134
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 5
Server version: 5.7.31 MySQL Community Server (GPL)
Copyright (c) 2000, 2020, 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>
- 配置主数据库
//修改配置文件,加上最后两行
[root@master ~]# vim /etc/my.cnf
[mysqld]
basedir = /usr/local/mysql
datadir = /data/3306
socket = /tmp/mysql.sock
port = 3306
pid-file = /data/3306/mysql.pid
user = mysql
skip-name-resolve
server-id = 10 //数据库服务器唯一标识符,主库的server-id值必须比从库的小
log-bin = mysql_bin //启用binlog日志
[root@master ~]# service mysqld restart //重启服务
Shutting down MySQL.... SUCCESS!
Starting MySQL. SUCCESS!
mysql> mysql> show master status; //查看主库的状态
+------------------+----------+--------------+------------------+-------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+------------------+----------+--------------+------------------+-------------------+
| mysql_bin.000001 | 154 | | | |
+------------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)
- 配置从数据库
//修改配置文件,加上最后两行
[root@slave ~]# vim /etc/my.cnf
[mysqld]
basedir = /usr/local/mysql
datadir = /data/3306
socket = /tmp/mysql.sock
port = 3306
pid-file = /data/3306/mysql.pid
user = mysql
skip-name-resolve
server-id = 20 //设置从库的唯一标识符,从库的server-id值必须大于主库的该值
relay-log = myreplay //启用中继日志relay-log
[root@slave ~]# service mysqld restart
Shutting down MySQL.. SUCCESS!
Starting MySQL. SUCCESS!
[root@slave ~]# mysql -uroot -p123456 //进入从库本机
//master的主机,用户,密码,文件日志,请求的位置
mysql> change master to master_host='192.168.152.134',master_user='repl',master_password='repl123',master_log_file='mysql_bin.000001',master_log_pos=154;
Query OK, 0 rows affected, 2 warnings (0.02 sec)
mysql> start slave; //开启从库
Query OK, 0 rows affected (0.00 sec)
mysql> show slave status\G //查看从服务器状态
*************************** 1. row ***************************
Slave_IO_State: Waiting for master to send event
Master_Host: 192.168.152.134
Master_User: repl
Master_Port: 3306
Connect_Retry: 60
Master_Log_File: mysql_bin.000001
Read_Master_Log_Pos: 154
Relay_Log_File: myreplay.000002
Relay_Log_Pos: 320
Relay_Master_Log_File: mysql_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: 154
Relay_Log_Space: 520
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: 10
Master_UUID: 222a5faa-19b7-11eb-a794-000c29d19610
Master_Info_File: /data/3306/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)
检测验证
- 在主服务器上创建数据库school,创建student表,插入内容
mysql> create database school;
Query OK, 1 row affected (0.00 sec)
mysql> use school;
Database changed
mysql> create table student(id int not null primary key auto_increment,name varchar(50),age tinyint);
Query OK, 0 rows affected (0.02 sec)
mysql> desc student;
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(50) | YES | | NULL | |
| age | tinyint(4) | YES | | NULL | |
+-------+-------------+------+-----+---------+----------------+
3 rows in set (0.02 sec)
mysql> insert student(name,age) values('zhangshan',20),('lisi',19),('wangwu',22);
Query OK, 3 rows affected (0.00 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> select * from student;
+----+-----------+------+
| id | name | age |
+----+-----------+------+
| 1 | zhangshan | 20 |
| 2 | lisi | 19 |
| 3 | wangwu | 22 |
+----+-----------+------+
3 rows in set (0.00 sec)
- 在从数据库查看数据是否同步
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| school |
| sys |
+--------------------+
5 rows in set (0.00 sec)
mysql> select * from school.student;
+----+-----------+------+
| id | name | age |
+----+-----------+------+
| 1 | zhangshan | 20 |
| 2 | lisi | 19 |
| 3 | wangwu | 22 |
+----+-----------+------+
3 rows in set (0.00 sec)
5.mysql主从配置
需求,环境说明同上一致,主数据库改为有数据,从数据库无数据
MySQL安装同上一致,分别在主从两台服务器上安装mysql-5.7
版本
为确保从数据库与主数据库里的数据一样,先全备主数据库并还原到从数据库中
- 在主数据库上创建数据库school,创建表格student,插入内容
mysql> create database school;
Query OK, 1 row affected (0.00 sec)
mysql> use school;
Database changed
mysql> create table student(id int not null primary key auto_increment,name varchar(50),age tinyint);
Query OK, 0 rows affected (0.02 sec)
mysql> insert student(name,age) values('xiaozhan',19),('lixian',22),('wangyibo',18),('zhuyilong',26);
Query OK, 4 rows affected (0.01 sec)
Records: 4 Duplicates: 0 Warnings: 0
mysql> select * from student;
+----+-----------+------+
| id | name | age |
+----+-----------+------+
| 1 | xiaozhan | 19 |
| 2 | lixian | 22 |
| 3 | wangyibo | 18 |
| 4 | zhuyilong | 26 |
+----+-----------+------+
4 rows in set (0.00 sec)
- 给主库读锁,全量备份,传输备份到从库
//全备主库时需要另开一个终端,给数据库加上读锁,避免在备份期间有其他人在写入导致数据不一致
mysql> flush tables with read lock;
Query OK, 0 rows affected (0.01 sec)
//全量备份主库
[root@localhost ~]# mysqldump -uroot -p123456 --all-databases > all.sql
mysqldump: [Warning] Using a password on the command line interface can be insecure.
[root@localhost ~]# ls
all.sql anaconda-ks.cfg mysql.22
//将备份文件传送到从库的家目录
[root@localhost ~]# scp all.sql 192.168.152.135:~
root@192.168.152.135's password:
all.sql 100% 841KB 37.3MB/s 00:00
- 从库恢复备份,查看状态,此时主库从库数据一致
//查看当前从库数据库
mysql -uroot -p123456 -e 'show databases;'
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sys |
+--------------------+
4 rows in set (0.00 sec)
//在从库上恢复全量备份
[root@localhost ~]# mysql -uroot -p123456 < all.sql
mysql: [Warning] Using a password on the command line interface can be insecure.
//再查看当前从数据库,多了个school库和student表
[root@localhost ~]# mysql -uroot -p123456 -e 'show databases;'
mysql: [Warning] Using a password on the command line interface can be insecure.
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| school |
| sys |
+--------------------+
[root@localhost ~]# mysql -uroot -p123456 -e 'select * from school.student;'
mysql: [Warning] Using a password on the command line interface can be insecure.
+----+-----------+------+
| id | name | age |
+----+-----------+------+
| 1 | xiaozhan | 19 |
| 2 | lixian | 22 |
| 3 | wangyibo | 18 |
| 4 | zhuyilong | 26 |
+----+-----------+------+
mysql> flush tables with read lock; //打开读锁的终端
Query OK, 0 rows affected (0.01 sec)
mysql> quit //退出就代表解锁数据库
Bye
- 在主数据库创建一个同步账户授权给从数据库使用
//创建同步账户名repl,授权给135主机同步,密码为repl123
mysql> grant replication slave on *.* to repl@192.168.152.135 identified by 'repl123';
Query OK, 0 rows affected, 1 warning (0.01 sec)
mysql> flush privileges; //刷新权限
Query OK, 0 rows affected (0.00 sec)
//修改配置,加上最后两行
[root@localhost ~]# vim /etc/my.cnf
[mysqld]
basedir = /usr/local/mysql
datadir = /data/3306
socket = /tmp/mysql.sock
port = 3306
pid-file = /data/3306/mysql.pid
user = mysql
skip-name-resolve
log-bin = mysql_bin
server-id = 10
//重启服务
[root@localhost ~]# service mysqld restart
Shutting down MySQL.... SUCCESS!
Starting MySQL. SUCCESS!
//查看master状态
mysql> mysql> show master status;
+------------------+----------+--------------+------------------+-------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+------------------+----------+--------------+------------------+-------------------+
| mysql_bin.000001 | 154 | | | |
+------------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)
- 从数据库修改配置
//加上最后两行内容
[root@localhost ~]# vim /etc/my.cnf
[mysqld]
basedir = /usr/local/mysql
datadir = /data/3306
socket = /tmp/mysql.sock
port = 3306
pid-file = /data/3306/mysql.pid
user = mysql
skip-name-resolve
relay-log = myrelay
server-id = 20
//重启服务
[root@localhost ~]# service mysqld restart
Shutting down MySQL.. SUCCESS!
Starting MySQL. SUCCESS!
//master的主机,用户,密码,文件日志,请求的位置
mysql> change master to master_host='192.168.152.134',master_user='repl',master_password='repl123',master_log_file='mysql_bin.000001',master_log_pos=154;
Query OK, 0 rows affected, 2 warnings (0.02 sec)
mysql> start slave; //启动从库
Query OK, 0 rows affected (0.00 sec)
mysql> show slave status\G //查看从服务器状态
*************************** 1. row ***************************
Slave_IO_State: Waiting for master to send event
Master_Host: 192.168.152.134
Master_User: repl
Master_Port: 3306
Connect_Retry: 60
Master_Log_File: mysql_bin.000001
Read_Master_Log_Pos: 154
Relay_Log_File: myrelay.000002
Relay_Log_Pos: 320
Relay_Master_Log_File: mysql_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: 154
Relay_Log_Space: 519
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: 10
Master_UUID: 050f5ad6-19c5-11eb-b89b-000c29d19610
Master_Info_File: /data/3306/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)
- 检测验证
//在主库上school.student里插入两条数据
mysql> insert school.student(name,age) value('yiyangqianxi',18),('zhangyixing',27);
Query OK, 2 rows affected (0.03 sec)
Records: 2 Duplicates: 0 Warnings: 0
//查看从库school.student内容,与主库同步一致
mysql> select * from school.student;
+----+--------------+------+
| id | name | age |
+----+--------------+------+
| 1 | xiaozhan | 19 |
| 2 | lixian | 22 |
| 3 | wangyibo | 18 |
| 4 | zhuyilong | 26 |
| 5 | yiyangqianxi | 18 |
| 6 | zhangyixing | 27 |
+----+--------------+------+
6 rows in set (0.00 sec)
//查看主库master表状态
mysql> show master status;
+------------------+----------+--------------+------------------+-------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+------------------+----------+--------------+------------------+-------------------+
| mysql_bin.000001 | 446 | | | |
+------------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)