MySql教程

MySQL主从复制

本文主要是介绍MySQL主从复制,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

MySQL主从

主从介绍

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

主从作用

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

主从形式

  • 一主一从
  • 主主复制
  • 一主多从---扩展系统读取的性能,因为读是在从库读取的
  • 多主一从---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主从配置实例:

//先查看主库有哪些库
[root@master ~]# mysql -uroot -pzs123! -e 'show databases;'
mysql: [Warning] Using a password on the command line interface can be insecure.
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+

//再查看从库有哪些库
[root@servera ~]# mysql -uroot -pzs123! -e 'show databases;'
mysql: [Warning] Using a password on the command line interface can be insecure.
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+

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

授权
mysql> grant replication slave on *.* to 'repl'@'192.168.145.170' identified by'repl123!'
    -> ;
Query OK, 0 rows affected, 1 warning (0.00 sec)

刷新
mysql> flush privileges;
Query OK, 0 rows affected (0.01 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/mysqld.pid
skip-name-resolve

# replication slave config
log-bin = mysql_bin
server-id = 10


重启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@servera ~]# cat /etc/my.cnf 
[mysqld]
port = 3306
basedir = /usr/local/mysql
datadir = /opt/data
socket = /tmp/mysql.sock
pid-file = /opt/data/mysqld.pid
skip-name-resolve

# replication slave config
server-id = 20
relay-log = mysql_relay

重启从库的mysql服务
[root@servera ~]# service mysqld restart 
Shutting down MySQL.. SUCCESS! 
Starting MySQL. SUCCESS! 

配置并启动主从复制
mysql> change master to
    -> master_host='192.168.145.169',
    -> 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.00 sec)

查看从服务器状态
mysql> show slave status\G
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.145.169
                  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.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: 523
              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: 2532827f-09a2-11ec-9fd2-000c298fc665
             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)

测试验证

主服务器上创建zs数据库
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.00 sec)

mysql> create database zs;
Query OK, 1 row affected (0.00 sec)

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

从服务器查看数据库是否同步
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
| zs                 |
+--------------------+
5 rows in set (0.00 sec)

第二种方式

主数据库上面有数据
查看主数据库有哪些库
[root@master ~]# mysql -uroot -pzs123! -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@servera ~]# mysql -uroot -pzs123! -e 'show databases;'
mysql: [Warning] Using a password on the command line interface can be insecure.
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+

全备主库
全备主库时需要另开一个终端,给数据库加上读锁,避免在备份期间有其他人在写入导致数据不一致
mysql> flush tables with read lock;
Query OK, 0 rows affected (0.01 sec)

测试读锁
mysql> show processlist;
+----+------+-----------+------+---------+------+------------------------------+----------------------+
| Id | User | Host      | db   | Command | Time | State                        | Info                 |
+----+------+-----------+------+---------+------+------------------------------+----------------------+
|  6 | root | localhost | NULL | Query   |    0 | starting                     | show processlist     |
|  7 | root | localhost | NULL | Query   |   17 | Waiting for global read lock | create database info |
+----+------+-----------+------+---------+------+------------------------------+----------------------+
2 rows in set (0.00 sec)

终止命令
mysql> kill 7;
Query OK, 0 rows affected (0.00 sec)

mysql> show processlist;
+----+------+-----------+------+---------+------+----------+------------------+
| Id | User | Host      | db   | Command | Time | State    | Info             |
+----+------+-----------+------+---------+------+----------+------------------+
|  6 | root | localhost | NULL | Query   |    0 | starting | show processlist |
+----+------+-----------+------+---------+------+----------+------------------+
1 row in set (0.00 sec)

备份文件并将备份文件传送到从库
[root@master ~]# mysqldump -uroot -pzs123! --all-databases > all.sql
mysqldump: [Warning] Using a password on the command line interface can be insecure.

scp all.sql 192.168.145.170:/root/
The authenticity of host '192.168.145.170 (192.168.145.170)' can't be established.
ECDSA key fingerprint is SHA256:t40x15ktcpMljOGJDYGl/mBzhl7pKNTCrzQ4D5mLaos.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.145.170' (ECDSA) to the list of known hosts.
root@192.168.145.170's password: 
Permission denied, please try again.
root@192.168.145.170's password: 
Permission denied, please try again.
root@192.168.145.170's password: 
all.sql                                            100%  853KB  60.8MB/s   00:00   

从服务器恢复备份并查看
[root@servera ~]# ls
公共  视频  文档  音乐  all.sql          initial-setup-ks.cfg
模板  图片  下载  桌面  anaconda-ks.cfg  pass
[root@servera ~]# mysql -uroot -pzs123! < all.sql 
mysql: [Warning] Using a password on the command line interface can be insecure.
[root@servera ~]# mysql -uroot -pzs123! -e 'show databases;'
mysql: [Warning] Using a password on the command line interface can be insecure.
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| school             |
| sys                |
+--------------------+

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

mysql> grant replication slave on *.* to 'repl'@'192.168.145.170' identified by 'repl123!';
Query OK, 0 rows affected, 1 warning (7.70 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/mysqld.pid
skip-name-resolve

server-id = 10
log-bin = mysql_bin

重启服务
[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@servera ~]# cat /etc/my.cnf 
[mysqld]
port = 3306
basedir = /usr/local/mysql
datadir = /opt/data
socket = /tmp/mysql.sock
pid-file = /opt/data/mysqld.pid
skip-name-resolve

server-id = 20
relay-log = mysql-relay

重启服务
[root@servera ~]# service mysqld restart 
Shutting down MySQL.. SUCCESS! 
Starting MySQL. SUCCESS! 

配置并启动主从复制
mysql> change master to
    -> master_host='192.168.145.169',
    -> 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.00 sec)

查看从服务器状态
mysql> show slave status\G
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.145.169
                  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.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: 523
              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: 148a6b3c-09ac-11ec-8dfc-000c298fc665
             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 |
| school             |
| sys                |
+--------------------+
5 rows in set (0.00 sec)

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 student;
+----+----------+------+
| id | name     | age  |
+----+----------+------+
|  1 | tom      |   10 |
|  2 | zhangsan |   20 |
|  3 | lisi     |   15 |
+----+----------+------+
3 rows in set (0.00 sec)

查看从服务器数据
mysql> select * from student;
+----+----------+------+
| id | name     | age  |
+----+----------+------+
|  1 | tom      |   10 |
|  2 | zhangsan |   20 |
|  3 | lisi     |   15 |
+----+----------+------+
3 rows in set (0.00 sec)

主服务器插入数据
mysql> insert student(name,age) value('wangwu',28);
Query OK, 1 row affected (0.01 sec)

mysql> select * from student;
+----+----------+------+
| id | name     | age  |
+----+----------+------+
|  1 | tom      |   10 |
|  2 | zhangsan |   20 |
|  3 | lisi     |   15 |
|  4 | wangwu   |   28 |
+----+----------+------+
4 rows in set (0.00 sec)

从服务器查看数据
mysql> select * from student;
+----+----------+------+
| id | name     | age  |
+----+----------+------+
|  1 | tom      |   10 |
|  2 | zhangsan |   20 |
|  3 | lisi     |   15 |
|  4 | wangwu   |   28 |
+----+----------+------+
4 rows in set (0.00 sec)
这篇关于MySQL主从复制的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!