1. 程式人生 > >mysql主從配置實現一主一從讀寫分離

mysql主從配置實現一主一從讀寫分離

配置文件 狀態 main ado man datadir lai community more

主從介紹

定義

  • Mysql主從又叫Replication、AB復制。簡單講就是A與B兩臺機器做主從後,在A上寫數據,另外一臺B也會跟著寫數據,實現數據實時同步
  • mysql主從是基於binlog,主上需開啟binlog才能進行主從
  • 主從過程大概有3個步驟

    • 主將更改操作記錄到binlog裏
    • 從將主的binlog事件(sql語句) 同步本機上並記錄在relaylog裏
    • 從根據relaylog裏面的sql語句按順序執行
  • 主上有一個log dump線程,用來和從的I/O 線程傳遞binlog
  • 從上有兩個線程,其中 I/O線程用來同步主的binlog裏面的sql語句落地

    主從的應用場景:

    數據的高可用。(主:作為讀寫數據,從:實時同步,當主宕機時,從 也可以及時提供服務)

數據的負載均衡。(客戶從 從 這臺機器上讀取數據(但是不

主從作用

  • 實時災備,用於故障切換
  • 讀寫分離,提供查詢服務
  • 備份,避免影響業務

    主從形式

    技術分享圖片

  • 一主一從
  • 主主復制
  • 一主多從---擴展系統讀取的性能,因為讀是在從庫讀取的
  • 多主一從---5.7版本開始支持
  • 聯級復制

    主從復制原理

    技術分享圖片

主從復制步驟

  • 主庫將所有的寫操作記錄在binlog日誌中,並生成log dump線程,將binlog日誌傳給從庫的I/O線程
  • 從庫生成兩個線程,一個是I/O線程,另一個是SQL線程

    • I/O線程去請求主庫的binlog日誌,並將binlog日誌中的文件寫入relay log(中繼日誌)中
    • SQL線程會讀取relay loy中的內容,並解析成具體的操作,來實現主從的操作一致,達到最終數據一致的目的

      主從復制配置

      主從復制配置步驟:

      1. 確保從數據庫與主數據庫裏的數據一致
      2. 在主數據庫裏創建一個同步賬戶授權給從數據庫使用
      3. 配合主數據庫(修改配置文件)
        4.配置從數據庫(修改配置文件)

        需求

        搭建兩臺MYSQL服務器,一臺作為主服務器,一臺作為從服務器,主服務器進行寫操作,從服務器進行讀操作

        環境說明

數據庫角色 IP 應用與系統 有無數據
主數據庫 192.168.24.18 centos7 mysql-5.7
從數據庫 192.168.24.129 centos7 mysql-5.7

在兩臺服務器上都按裝mysql

具體配置查看《mysql進階簡單解析》

mysql主從配置

確保從數據庫與主數據庫的數據一樣

先在主數據庫創建所需要同步的庫和表

[root@linfan ~]# mysql -uroot -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.7.22 MySQL Community Server (GPL)

Copyright (c) 2000, 2018, 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> create database doudou;
Query OK, 1 row affected (0.03 sec)

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

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

mysql> use doudou;
Database changed
mysql> create table tom (id int not null,name varchar(100) not null,age tinyint);
Query OK, 0 rows affected (0.22 sec)
mysql> insert tom(id,name,age) values(1,"lisi",6),(2,"waangwu",5),(3,"zhaotie",9);
Query OK, 3 rows affected (0.07 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> select * from tom;
+----+---------+------+
| id | name    | age  |
+----+---------+------+
|  1 | lisi    |    6 |
|  2 | waangwu |    5 |
|  3 | zhaotie |    9 |
+----+---------+------+
3 rows in set (0.01 sec)

mysql>                   

備份主庫
備份主庫時需要另開一個終端,給數據庫上讀鎖,避免在備份期間有其他人在寫入導致數據同步的不一致

[root@linfan ~]# 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.22 MySQL Community Server (GPL)

Copyright (c) 2000, 2018, 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> flush tables with read lock;
Query OK, 0 rows affected (0.17 sec)

mysql> //此鎖表的終端必須在備份完成以後才能退出(退出鎖表失效)                            

備份主庫並將備份文件傳送到從庫

[root@linfan ~]# mysqldump -uroot -plinfan123 --all-databases >/opt/all-20180907.sql
mysqldump: [Warning] Using a password on the command line interface can be insecure.
[root@linfan ~]# ls /opt/
all-20180907.sql  data
[root@linfan ~]# scp /opt/all-20180907.sql [email protected]:/opt/
The authenticity of host ‘192.168.24.130 (192.168.24.130)‘ can‘t be established.
ECDSA key fingerprint is SHA256:w+sgREnQRuhBiqS0qL9wlAImCSmvSQ6KnNqW6N3znJ0.
ECDSA key fingerprint is MD5:f0:fd:ea:c7:97:83:f0:b0:03:84:d2:a6:0a:23:12:e0.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added ‘192.168.24.130‘ (ECDSA) to the list of known hosts.
[email protected]‘s password:
all-20180907.sql                                                                        100%

解除主庫的鎖表狀態,直接退出交互式界面即可


mysql> quit
Bye

在從庫上恢復主庫的備份並查看是否與主庫的數據保持一致

[root@linfan ~]# mysql -uroot -plinfan123 < /opt/all-20180907.sql
mysql: [Warning] Using a password on the command line interface can be insecure.
[root@linfan ~]# mysql -uroot -plinfan123
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 4
Server version: 5.7.22 MySQL Community Server (GPL)

Copyright (c) 2000, 2018, 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> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| doudou             |
| job                |
| mary               |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
7 rows in set (0.01 sec)

mysql> use doudou
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 tom;
+----+---------+------+
| id | name    | age  |
+----+---------+------+
|  1 | lisi    |    6 |
|  2 | waangwu |    5 |
|  3 | zhaotie |    9 |
+----+---------+------+
3 rows in set (0.00 sec)

在主數據庫創建一個同步賬戶授權給從數據使用

[root@linfan ~]# mysql -uroot -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 6
Server version: 5.7.22 MySQL Community Server (GPL)

Copyright (c) 2000, 2018, 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> create user ‘repl‘@‘192.168.24.130‘ identified by ‘123456‘;
Query OK, 0 rows affected (0.04 sec)

mysql> grant replication slave on *.* to ‘repl‘@‘192.168.24.130‘;
Query OK, 0 rows affected (0.00 sec)

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

配置主數據庫

編輯配置文件

[root@linfan ~]# vim /etc/my.cnf
[root@linfan ~]# cat /etc/my.cnf
[mysqld]
basedir = /usr/local/mysql
datadir = /opt/data
socket = /tmp/mysql.sock
port = 3306
pid-file = /opt/data/mysql.pid
user = mysql
skip-name-resolve
//添加以下內容
log-bin=mysql-bin //啟用binlog日誌
server-id=1 //主數據庫服務器唯一標識符 主的必須必從大
log-error=/opt/data/mysql.log

重啟mysql服務

[root@linfan ~]# service mysqld restart
Shutting down MySQL... SUCCESS!
Starting MySQL.Logging to ‘/opt/data/mysql.log‘.
.......... SUCCESS! 
[root@linfan ~]# ss -natl
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> 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@linfan ~]# cat /etc/my.cnf
[mysqld]
basedir = /usr/local/mysql
datadir = /opt/data
socket = /tmp/mysql.sock
port = 3306
pid-file = /opt/data/mysql.pid
user = mysql
skip-name-resolve
//添加以下內容:
server-id=2 //設置從庫的唯一標識符 從的必須比主小
relay-log=mysql-relay-bin //啟用中繼日誌relay log
error-log=/opt/data/mysql.log

重啟從庫的mysql服務

[root@linfan ~]# service mysqld restart
Shutting down MySQL... SUCCESS!
Starting MySQL.Logging to ‘/opt/data/mysql.log‘.
.......... SUCCESS! 
[root@linfan ~]# ss -natl
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.24.128‘,
    -> master_user=‘repl‘,
    -> master_password=‘123456‘,
    -> 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.24.128
                  Master_User: repl
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000001
          Read_Master_Log_Pos: 154
               Relay_Log_File: linfan-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: 528
              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: 3396fe35-b1e1-11e8-81bb-000c292340f6
             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) 

測試驗證

在主服務器的doudou庫的tom表插入數據:

mysql> use doudou;
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 tom;
+----+---------+------+
| id | name    | age  |
+----+---------+------+
|  1 | lisi    |    6 |
|  2 | waangwu |    5 |
|  3 | zhaotie |    9 |
+----+---------+------+
3 rows in set (0.00 sec)

mysql> insert tom(id,name,age) value (4,"mary",18);
Query OK, 1 row affected (0.10 sec)

mysql> select * from tom;
+----+---------+------+
| id | name    | age  |
+----+---------+------+
|  1 | lisi    |    6 |
|  2 | waangwu |    5 |
|  3 | zhaotie |    9 |
|  4 | mary    |   18 |
+----+---------+------+
4 rows in set (0.00 sec)

在從數據庫查看是否數據同步

mysql> use doudou;
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 tom;
+----+---------+------+
| id | name    | age  |
+----+---------+------+
|  1 | lisi    |    6 |
|  2 | waangwu |    5 |
|  3 | zhaotie |    9 |
|  4 | mary    |   18 |
+----+---------+------+
4 rows in set (0.00 sec)

mysql主從配置實現一主一從讀寫分離