MySQL主从
主从简介
在现代企业中,数据显得尤为重要,而存储数据的数据库选择又五花八门,但无论是何种数据库,均存在着一种隐患。
- 用一台数据库存放数据,若此数据库服务器宕机了导致数据丢失怎么办?
- 业务量大了,数据多了,访问的人多了,一台数据库无法保证服务质量了怎么办?
主从作用
- 实时灾备,用于故障切换
- 读写分离,提供查询服务
- 备份,避免影响业务
主从形式
- 一主一从
- 主主复制
- 一主多从—扩展系统读取的性能,因为读是在从库读取的
- 多主一从—5.7开始支持
- 联级复制
主从复制原理
主从复制配置步骤:
- 确保从数据库与主数据库里的数据一样
- 在主数据库里创建一个同步账号授权给从数据库使用
- 配置主数据库(修改配置文件)
- 配置从数据库(修改配置文件)
需求:
搭建两台MySQL服务器,一台作为主服务器,一台作为从服务器,主服务器进行写操作,从服务器进行读操作
实验环境:
数据库角色 | IP | 有无数据 |
---|---|---|
主数据库 | 192.168.72.131 | 有数据 |
从数据库 | 192.168.72.132 | 无数据 |
mysql主从配置
- 创建用户和组
[root@node2 ~]# groupadd -r mysql
[root@node2 ~]# useradd -M -s /sbin/nologin -g mysql mysql
- 解压软件至/usr/local/
[root@master ~]# tar xf mysql-5.7.35-linux-glibc2.12-x86_64.tar.gz -C /usr/local/
[root@master ~]# ls /usr/local/
bin games lib libexec sbin src
etc include lib64 mysql-5.7.35-linux-glibc2.12-x86_64 share
[root@master ~]# cd /usr/local/
[root@master local]# ln -sv mysql-5.7.35-linux-glibc2.12-x86_64/ mysql //创建软链接
'mysql' -> 'mysql-5.7.35-linux-glibc2.12-x86_64/'
[root@master local]# ll
总用量 0
drwxr-xr-x. 2 root root 6 8月 12 2018 bin
drwxr-xr-x. 2 root root 6 8月 12 2018 etc
drwxr-xr-x. 2 root root 6 8月 12 2018 games
drwxr-xr-x. 2 root root 6 8月 12 2018 include
drwxr-xr-x. 2 root root 6 8月 12 2018 lib
drwxr-xr-x. 2 root root 6 8月 12 2018 lib64
drwxr-xr-x. 2 root root 6 8月 12 2018 libexec
lrwxrwxrwx. 1 root root 36 8月 30 05:17 mysql -> mysql-5.7.35-linux-glibc2.12-x86_64/
drwxr-xr-x. 9 root root 129 8月 30 05:15 mysql-5.7.35-linux-glibc2.12-x86_64
drwxr-xr-x. 2 root root 6 8月 12 2018 sbin
drwxr-xr-x. 5 root root 49 11月 2 2020 share
drwxr-xr-x. 2 root root 6 8月 12 2018 src
- 修改目录/usr/local/mysql的属主属组
[root@master local]# chown -R mysql.mysql /usr/local/mysql
[root@master local]# ll /usr/local/mysql -d
lrwxrwxrwx. 1 mysql mysql 36 8月 30 05:17 /usr/local/mysql -> mysql-5.7.35-linux-glibc2.12-x86_64/
[root@master local]# ll
总用量 0
drwxr-xr-x. 2 root root 6 8月 12 2018 bin
drwxr-xr-x. 2 root root 6 8月 12 2018 etc
drwxr-xr-x. 2 root root 6 8月 12 2018 games
drwxr-xr-x. 2 root root 6 8月 12 2018 include
drwxr-xr-x. 2 root root 6 8月 12 2018 lib
drwxr-xr-x. 2 root root 6 8月 12 2018 lib64
drwxr-xr-x. 2 root root 6 8月 12 2018 libexec
lrwxrwxrwx. 1 mysql mysql 36 8月 30 05:17 mysql -> mysql-5.7.35-linux-glibc2.12-x86_64/
drwxr-xr-x. 9 root root 129 8月 30 05:15 mysql-5.7.35-linux-glibc2.12-x86_64
drwxr-xr-x. 2 root root 6 8月 12 2018 sbin
drwxr-xr-x. 5 root root 49 11月 2 2020 share
drwxr-xr-x. 2 root root 6 8月 12 2018 src
- 添加环境变量
[root@master local]# ls /usr/local/mysql
bin docs include lib LICENSE man README share support-files
[root@master local]# echo 'export PATH=/usr/local/mysql/bin:$PATH' > /etc/profile.d/mysql.sh
[root@master local]# . /etc/profile.d/mysql.sh
[root@master local]# echo $PATH
/usr/local/mysql/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
- 建立数据存放目录
[root@master local]# mkdir /opt/data
[root@master local]# chown -R mysql.mysql /opt/data
[root@master local]# ll /opt/
总用量 0
drwxr-xr-x. 2 mysql mysql 6 8月 30 05:38 data
- 初始化数据库
[root@master local]# /usr/local/mysql/bin/mysqld --initialize --user=mysql --datadir=/opt/data/
2021-08-30T02:29:39.606440Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2021-08-30T02:29:39.792855Z 0 [Warning] InnoDB: New log files created, LSN=45790
2021-08-30T02:29:39.822708Z 0 [Warning] InnoDB: Creating foreign key constraint system tables.
2021-08-30T02:29:39.878022Z 0 [Warning] No existing UUID has been found, so we assume that this is the first time that this server has been started. Generating a new UUID: 533a8e4b-0976-11ec-9f6d-000c2945ecb2.
2021-08-30T02:29:39.878746Z 0 [Warning] Gtid table is not ready to be used. Table 'mysql.gtid_executed' cannot be opened.
2021-08-30T02:29:40.267498Z 0 [Warning] A deprecated TLS version TLSv1 is enabled. Please use TLSv1.2 or higher.
2021-08-30T02:29:40.267516Z 0 [Warning] A deprecated TLS version TLSv1.1 is enabled. Please use TLSv1.2 or higher.
2021-08-30T02:29:40.268022Z 0 [Warning] CA certificate ca.pem is self signed.
2021-08-30T02:29:40.952843Z 1 [Note] A temporary password is generated for root@localhost: si=?PkWal068
- 生成配置文件
[root@master ~]# cat /etc/my.cnf
[mysqld]
port = 3306
basedir = /usr/local/mysql
datadir = /opt/data
socket = /tmp/mysql.sock
pid-file = /opt/data/mysql.pid
skip-name-resolve
- 写入mysql启动服务
[root@master ~]# cp -a /usr/local/mysql/support-files/mysql.server /etc/init.d/mysqld
[root@master ~]# cd /usr/local/mysql/support-files/
[root@master support-files]# ls
magic mysqld_multi.server mysql-log-rotate mysql.serverr
[root@master support-files]# vim /etc/init.d/mysqld
[root@master support-files]# cat /etc/init.d/mysqld
# If you change base dir, you must also change datadir. These may get
# overwritten by settings in the MySQL configuration files.
basedir=/usr/local/mysql
datadir=/opt/data
# Default value, in seconds, afterwhich the script should timeout waiting
# for server start.
- 启动mysql
[root@master ~]# service mysqld start
Starting MySQL.Logging to '/opt/data/master.err'.
SUCCESS!
[root@master ~]# ss -antl
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 0.0.0.0:111 0.0.0.0:*
LISTEN 0 32 192.168.122.1:53 0.0.0.0:*
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 5 127.0.0.1:631 0.0.0.0:*
LISTEN 0 128 127.0.0.1:6010 0.0.0.0:*
LISTEN 0 128 127.0.0.1:6011 0.0.0.0:*
LISTEN 0 80 *:3306 *:*
LISTEN 0 128 [::]:111 [::]:*
LISTEN 0 128 [::]:22 [::]:*
LISTEN 0 5 [::1]:631 [::]:*
LISTEN 0 128 [::1]:6010 [::]:*
LISTEN 0 128 [::1]:6011 [::]:*
- 修改数据库密码
[root@master ~]# mysql -uroot -p'si=?PkWal068;
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 2
Server version: 5.7.35
Copyright (c) 2000, 2021, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> set password = password('1');
Query OK, 0 rows affected, 1 warning (0.00 sec)
部署主从
//先查看主库有哪些库
[root@master ~]# mysql -uroot -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 5
Server version: 5.7.35 MySQL Community Server (GPL)
Copyright (c) 2000, 2021, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sys |
+--------------------+
4 rows in set (0.01 sec)
//再查看从库有哪些库
[root@slave ~]# mysql -uroot -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.7.35 MySQL Community Server (GPL)
Copyright (c) 2000, 2021, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sys |
+--------------------+
4 rows in set (0.00 sec)
在主数据库里创建一个同步账号授权给从数据库使用
mysql> create user 'repl'@'192.168.25.142' identified by 'repl123'; //创建账号
Query OK, 0 rows affected (0.01 sec)
mysql> grant replication slave on *.* to 'repl'@'192.168.25.142'; //授权
Query OK, 0 rows affected (0.00 sec)
mysql> flush privileges; //刷新
Query OK, 0 rows affected (0.00 sec)
配置主数据库
[root@master ~]# cat /etc/my.cnf
[mysqld]
port = 3306
basedir = /usr/local/mysql
datadir = /opt/data
socket = /tmp/mysql.sock
pid-file = /opt/data/mysql.pid
skip-name-resolve
log-bin=mysql-bin //启用binlog日志
server-id=10 //数据库服务器唯一标识符,主库的server-id值必须比从库的小
//重启mysql服务
[root@master ~]# service mysqld restart
Shutting down MySQL.. SUCCESS!
Starting MySQL. SUCCESS!
查看主库的状态
+------------------+----------+--------------+------------------+-------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+------------------+----------+--------------+------------------+-------------------+
| mysql-bin.000001 | 154 | | | |
+------------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)
配置从数据库
[root@slave ~]# cat /etc/my.cnf
[mysqld]
port = 3306
basedir = /usr/local/mysql
datadir = /opt/data
socket = /tmp/mysql.sock
pid-file = /opt/data/mysql.pid
skip-name-resolve
server-id=20 //设置从库的唯一标识符,从库的server-id值必须大于主库的该值
relay-log=mysql-relay-bin // 启用中继日志relay-log
//重启从库的mysql服务
配置并启动主从复制
[root@slave ~]# mysql -uroot -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.35 MySQL Community Server (GPL)
Copyright (c) 2000, 2021, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
mysql> change master to
-> master_Host='192.168.72.131',
-> master_user='repl',
-> master_password='repl123',
-> master_log_file='mysql-bin.000001',
-> master_log_pos=154;
Query OK, 0 rows affected, 2 warnings (0.01 sec)
mysql> start slave; //打开主从
Query OK, 0 rows affected (0.01 sec)
mysql> show slave status\G //查看slavs状态
*************************** 1. row ***************************
Slave_IO_State: Waiting for master to send event
Master_Host: 192.168.72.131
Master_User: repl
Master_Port: 3306
Connect_Retry: 60
Master_Log_File: mysql-bin.000001
Read_Master_Log_Pos: 154
Relay_Log_File: mysql-relay-bin.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: 527
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: 533a8e4b-0976-11ec-9f6d-000c2945ecb2
Master_Info_File: /opt/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)
测试验证
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sys |
+--------------------+
4 rows in set (0.00 sec)
mysql> create database student;
Query OK, 1 row affected (0.01 sec)
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| student |
| sys |
+--------------------+
5 rows in set (0.00 sec)
在从数据库中查看数据是否同步
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| student |
| sys |
+--------------------+
5 rows in set (0.00 sec)
模拟主数据库有数据
mysql> create database student;
Query OK, 1 row affected (0.00 sec)
mysql> use student;
Database changed
mysql> create table LL(id int not null primary key auto_increment,name varchar(50) not null,age tinyint);
Query OK, 0 rows affected (0.00 sec)
mysql> insert LL(name,age) values('tom',10),('jerry',20),('lisi',30);
Query OK, 3 rows affected (0.01 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> select * from LL;
+----+-------+------+
| id | name | age |
+----+-------+------+
| 1 | tom | 10 |
| 2 | jerry | 20 |
| 3 | lisi | 30 |
+----+-------+------+
3 rows in set (0.00 sec)
全备主库
全备主库时需要另开一个终端,给数据库加上读锁,避免在备份期间有其他人在写入导致数据不一致
mysql> flush tables with read lock;
Query OK, 0 rows affected (0.00 sec)
//此锁表的终端必须在备份完成以后才能退出
备份主库并将备份文件传送到从库
[root@master ~]# mysqldump -uroot -p1 --all-databases > /opt/all-20210830.sql
mysqldump: [Warning] Using a password on the command line interface can be insecure.
[root@master ~]# ls /opt/
all-20210830.sql data
[root@master ~]# scp /opt/all-20210830.sql root@192.168.25.142:/opt/
The authenticity of host '192.168.72.132 (192.168.72.132)' can't be established.
ECDSA key fingerprint is SHA256:/SJbOLoOuH3estBrdxUtlQ56iKPhVSYumEVNVXmOye0.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '192.168.72.132' (ECDSA) to the list of known hosts.
root@192.168.72.132's password:
all-20210830.sql 100% 854KB 45.8MB/s 00:00
[root@slave ~]# ls /opt/
all-20210830.sql data
在从库上恢复主库的备份并查看从库有哪些库,确保与主库一致
[root@slave ~]# mysql -uroot -p1 < /opt/all-20210830.sql
mysql: [Warning] Using a password on the command line interface can be insecure.
[root@slave ~]# mysql -uroot -p1
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.35 MySQL Community Server (GPL)
Copyright (c) 2000, 2021, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| student |
| sys |
+--------------------+
5 rows in set (0.00 sec)
在主数据库里创建一个同步账号授权给从数据库使用
mysql> create user 'repl'@'192.168.72.132' identified by 'repl123'; //创建账号
Query OK, 0 rows affected (0.01 sec)
mysql> grant replication slave on *.* to 'repl'@'192.168.72.132'; //授权
Query OK, 0 rows affected (0.00 sec)
mysql> flush privileges; //刷新
Query OK, 0 rows affected (0.00 sec)
配置主数据库
[root@master ~]# cat /etc/my.cnf
[mysqld]
port = 3306
basedir = /usr/local/mysql
datadir = /opt/data
socket = /tmp/mysql.sock
pid-file = /opt/data/mysql.pid
skip-name-resolve
log-bin=mysql-bin //启用binlog日志
server-id=10 //数据库服务器唯一标识符,主库的server-id值必须比从库的小
//重启mysql服务
[root@master ~]# service mysqld restart
Shutting down MySQL.. SUCCESS!
Starting MySQL. SUCCESS!
查看主库的状态
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 ~]# cat /etc/my.cnf
[mysqld]
port = 3306
basedir = /usr/local/mysql
datadir = /opt/data
socket = /tmp/mysql.sock
pid-file = /opt/data/mysql.pid
skip-name-resolve
server-id=20 //设置从库的唯一标识符,从库的server-id值必须大于主库的该值
relay-log=mysql-relay-bin // 启用中继日志relay-log
//重启从库的mysql服务
配置并启动主从复制
[root@slave ~]# mysql -uroot -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.35 MySQL Community Server (GPL)
Copyright (c) 2000, 2021, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
mysql> change master to
-> master_Host='192.168.72.131',
-> master_user='repl',
-> master_password='repl123',
-> master_log_file='mysql-bin.000001',
-> master_log_pos=154;
Query OK, 0 rows affected, 2 warnings (0.01 sec)
mysql> start slave; //打开主从
Query OK, 0 rows affected (0.01 sec)
mysql> show slave status\G //查看slavs状态
*************************** 1. row ***************************
Slave_IO_State: Waiting for master to send event
Master_Host: 192.168.72.131
Master_User: repl
Master_Port: 3306
Connect_Retry: 60
Master_Log_File: mysql-bin.000001
Read_Master_Log_Pos: 154
Relay_Log_File: mysql-relay-bin.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: 527
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: 533a8e4b-0976-11ec-9f6d-000c2945ecb2
Master_Info_File: /opt/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)
测试验证
在主服务器上创建数据库shcool
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
|student |
| performance_schema |
| sys |
+--------------------+
4 rows in set (0.00 sec)
mysql> create database shcool;
Query OK, 1 row affected (0.01 sec)
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| student |
| shcool |
| sys |
+--------------------+
5 rows in set (0.00 sec)
在从数据库中查看数据是否同步
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| student |
| school |
| sys |
+--------------------+
5 rows in set (0.00 sec)