MySQL主从同步

导读:本篇文章讲解 MySQL主从同步,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

一. 主从简介

在现代企业中,数据显得尤为重要,而存储数据的数据库选择又五花八门,但无论是何种数据库,均存在着一种隐患。

想几个问题:

  • 用一台数据库存放数据,若此数据库服务器宕机了导致数据丢失怎么办?
  • 业务量大了,数据多了,访问的人多了,一台数据库无法保证服务质量了怎么办?

1.1 主从作用

  • 实时灾备,用于故障切换
  • 读写分离,提供查询服务
  • 备份,避免影响业务

1.2 主从形式

  • 一主一从
  • 主主复制
  • 一主多从—扩展系统读取的性能,因为读是在从库读取的
  • 多主一从—5.7开始支持
  • 联级复制

二. 主从复制原理

在这里插入图片描述
主从复制步骤:

  • 主库将所有的写操作记录到binlog日志中并生成一个log dump线程,将binlog日志传给从库的I/O线程
  • 从库生成两个线程,一个I/O线程,一个SQL线程
    • I/O线程去请求主库的binlog,并将得到的binlog日志写到relay log(中继日志) 文件中
    • SQL线程,会读取relay log文件中的日志,并解析成具体操作,来实现主从的操作一致,达到最终数据一致的目的

三. 主从复制配置

主从复制配置步骤:

  1. 确保从数据库与主数据库里的数据一样
  2. 在主数据库里创建一个同步账号授权给从数据库使用
  3. 配置主数据库(修改配置文件)
  4. 配置从数据库(修改配置文件)

需求:
搭建两台MySQL服务器,一台作为主服务器,一台作为从服务器,主服务器进行写操作,从服务器进行读操作

环境说明:

数据库角色 IP 应用与系统版本 有无数据
主数据库 192.168.91.129 mysql-5.7 有数据
从数据库 192.168.91.130 mysql-5.7 无数据

3.1 mysql安装

分别在主从两台服务器上安装mysql-5.7版本,此处略过安装步骤,若有疑问请参考《mysql基础》与《mysql进阶》两篇文章。

3.2 mysql主从配置

3.2.1 确保从数据库与主数据库里的数据一样

为确保从数据库与主数据库里的数据一样,先全备主数据库并还原到从数据库中

//先查看主库有哪些库
[root@localhost ~]# mysql -uroot -pgf123!
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 |
| gaofan             |
| mysql              |
| performance_schema |
| sys                |
| xiaoxiongxiong     |
+--------------------+
6 rows in set (0.00 sec)

mysql> select * from gaofan.csl;
+----+------+------+
| id | name | age  |
+----+------+------+
|  1 | chen |   20 |
|  2 | xu   |   18 |
+----+------+------+
2 rows in set (0.00 sec)


//再查看从库有哪些库
[root@localhost ~]# mysql -uroot -pgf123!
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.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> FLUSH TABLES WITH READ LOCK;
Query OK, 0 rows affected (0.00 sec)
//此锁表的终端必须在备份完成以后才能退出

//备份主库并将备份文件传送到从库
[root@localhost ~]# mysqldump -uroot -pgf123! --all-databases > /opt/all-`date +%F`.sql
mysqldump: [Warning] Using a password on the command line interface can be insecure.
[root@localhost ~]# ls /opt/
all-2021-08-30.sql
[root@localhost ~]# scp /opt/all-201808191200.sql root@172.16.12.129:/opt/
root@172.16.12.129's password:
all-201808191200.sql                              100%  786KB  10.6MB/s   00:00 

//解除主库的锁表状态,直接退出交互式界面即可
mysql> quit
Bye


//在从库上恢复主库的备份并查看从库有哪些库,确保与主库一致
[root@localhost ~]# mysql -uroot -pgf123! < /opt/all-2021-08-30.sql 
mysql: [Warning] Using a password on the command line interface can be insecure.
[root@localhost ~]# mysql -uroot -pgf123! -e  "show databases;"
mysql: [Warning] Using a password on the command line interface can be insecure.
+--------------------+
| Database           |
+--------------------+
| information_schema |
| gaofan             |
| mysql              |
| performance_schema |
| sys                |
| xiaoxiongxiong     |
+--------------------+
[root@localhost ~]# 

3.2.2 在主数据库里创建一个同步账号授权给从数据库使用

mysql> create user 'gaofan'@'192.168.91.130' identified by "gf123!";
Query OK, 0 rows affected (0.00 sec)

mysql> grant  replication slave on *.* to  'gaofan'@'192.168.153.130'  ;
Query OK, 0 rows affected (0.00 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

3.2.3 配置主数据库

[root@localhost ~]# vim /etc/my.cnf
//在[mysqld]这段的后面加上如下内容
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
log-bin=mysql-bin   //启用binlog日志
server-id=1     //数据库服务器唯一标识符,主库的server-id值必须比从库的大

symbolic-links=0

log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid 


//重启mysql服务
[root@localhost ~]# service mysqld restart
Shutting down MySQL.. SUCCESS! 
Starting MySQL. SUCCESS! 
[root@localhost ~]# ss -antl
State       Recv-Q Send-Q      Local Address:Port                     Peer Address:Port
LISTEN      0      128                     *:22                                  *:*
LISTEN      0      100             127.0.0.1:25                                  *:*
LISTEN      0      128                    :::22                                 :::*
LISTEN      0      100                   ::1:25                                 :::*
LISTEN      0      80                     :::3306                               :::* 


//查看主库的状态
[root@localhost ~]# mysql -uroot -pgf123!

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)

3.2.4 配置从数据库

[root@localhost ~]# vim /etc/my.cnf
//添加如下内容
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
server-id=2     //设置从库的唯一标识符,从库的server-id值必须小于主库的该值
relay-log=mysql-relay-bin       //启用中继日志relay-log

symbolic-links=0

log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid


//重启从库的mysql服务
[root@localhost ~]# service mysqld restart
Shutting down MySQL.. SUCCESS! 
Starting MySQL. SUCCESS! 
[root@localhost ~]# ss -antl
State      Recv-Q Send-Q           Local Address:Port                          Peer Address:Port
LISTEN     0      128                          *:22                                       *:*
LISTEN     0      100                  127.0.0.1:25                                       *:*
LISTEN     0      128                         :::22                                      :::*
LISTEN     0      100                        ::1:25                                      :::*
LISTEN     0      80                          :::3306                                    :::*




//配置并启动主从复制
mysql> change master to
    -> master_host='192.168.91.129' ,
    -> master_user='gaofan' ,
    -> master_password='gf123!' ,
    -> 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> start slave ;
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> show slave status\G
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.91.129
                  Master_User: gaofan
                  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
            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: 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: 1
                  Master_UUID: 8c77b785-0974-11ec-8d8a-000c29810dc2
             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)

3.2.5 测试验证

在主服务器的gaofan库的csl表中删除数据:

mysql> select * from gaofan.csl;
+----+------+------+
| id | name | age  |
+----+------+------+
|  1 | chen |   20 |
|  2 | xu   |   18 |
+----+------+------+
2 rows in set (0.01 sec)


mysql> delete from gaofan.csl  where name = 'chen' and age = 20;
Query OK, 1 row affected (0.00 sec)

mysql> 
mysql> select * from gaofan.csl;
+----+------+------+
| id | name | age  |
+----+------+------+
|  2 | xu   |   18 |
+----+------+------+
1 row in set (0.00 sec)

在从数据库中查看数据是否同步:

mysql> select * from gaofan.csl;
+----+------+------+
| id | name | age  |
+----+------+------+
|  2 | xu   |   18 |
+----+------+------+
1 row in set (0.00 sec)

四 新部署一个主从

4.1主库配置

授权一个用户给从库使用

[root@localhost ~]# mysql -uroot -pgf123!  
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.35-log 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> create user 'gaofan'@'%'  identified   by "gf123!" ;
Query OK, 0 rows affected (0.00 sec)

mysql> 
mysql> grant replication slave on *.* to 'gaofan'@'%' ;
Query OK, 0 rows affected (0.00 sec)


mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

修改配置文件

[root@localhost ~]# vim /etc/my.cnf
//在[mysqld]这段的后面加上如下内容
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
log-bin=mysql-bin   //启用binlog日志
server-id=1     //数据库服务器唯一标识符,主库的server-id值必须比从库的大

symbolic-links=0

log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid 


//重启mysql服务
[root@localhost ~]# service mysqld restart
Shutting down MySQL.. SUCCESS! 
Starting MySQL. SUCCESS! 
[root@localhost ~]# ss -antl
State       Recv-Q Send-Q      Local Address:Port                     Peer Address:Port
LISTEN      0      128                     *:22                                  *:*
LISTEN      0      100             127.0.0.1:25                                  *:*
LISTEN      0      128                    :::22                                 :::*
LISTEN      0      100                   ::1:25                                 :::*
LISTEN      0      80                     :::3306                               :::* 

4.2 从库配置

修改配置文件

[root@localhost ~]# vim /etc/my.cnf
//添加如下内容
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
server-id=2     //设置从库的唯一标识符,从库的server-id值必须小于主库的该值
relay-log=mysql-relay-bin       //启用中继日志relay-log

symbolic-links=0

log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid


//重启从库的mysql服务
[root@localhost ~]# service mysqld restart
Shutting down MySQL.. SUCCESS! 
Starting MySQL. SUCCESS! 
[root@localhost ~]# ss -antl
State      Recv-Q Send-Q           Local Address:Port                          Peer Address:Port
LISTEN     0      128                          *:22                                       *:*
LISTEN     0      100                  127.0.0.1:25                                       *:*
LISTEN     0      128                         :::22                                      :::*
LISTEN     0      100                        ::1:25                                      :::*
LISTEN     0      80                          :::3306                                    :::*

从库开启主从服务

mysql> change master to
    ->     -> master_host='192.168.91.129' ,
    ->     -> master_user='gaofan' ,
    ->     -> master_password='gf123!' ,
    ->     -> master_log_file='mysql-bin.000001'  ,
    ->     -> master_log_pos=154 ;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-> master_host='192.168.91.129' ,
    -> master_user='gaofan' ,
    -> mast' at line 2
mysql> change master to
    -> master_host='192.168.91.129' ,
    -> master_user='gaofan' ,
    -> master_password='gf123!' ,
    -> master_log_file='mysql-bin.000001'  ,
    -> master_log_pos=154 ;
Query OK, 0 rows affected, 2 warnings (0.00 sec)

mysql> 
mysql> 
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.91.129
                  Master_User: gaofan
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000009
          Read_Master_Log_Pos: 1165
               Relay_Log_File: mysql-relay-bin.000010
                Relay_Log_Pos: 1378
        Relay_Master_Log_File: mysql-bin.000009
             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: 1165
              Relay_Log_Space: 1798
              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: 1
                  Master_UUID: b736875b-097e-11ec-b557-000c29810dc2
             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> 
mysql> 
mysql> create database gaofan;
Query OK, 1 row affected (0.00 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| gaofan        	 |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
5 rows in set (0.00 sec)

//从库查看
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| gaofan             |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
5 rows in set (0.00 sec)





Query OK, 1 row affected (0.00 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| gaofan             |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
5 rows in set (0.00 sec)

//从库查看
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| gaofan             |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
5 rows in set (0.00 sec)

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/5639.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!