MySQL主從配置

MySQL主從介紹

  • MySQL主從又叫做Replication、AB複製。簡單講就是A和B兩臺機器做主從後,在A上寫數據,另外一臺B也會跟着寫數據,兩者數據實時同步的。
  • MySQL主從是基於binlog的,主上須開啓binlog才能進行主從。
  • 主從過程大致有3個步驟:
    1. 主將更改操作記錄到binlog裏;
    2. 從將主的binlog事件(sql語句)同步到從本機上並記錄在relaylog裏;
    3. 從根據relaylog裏面的sql語句按順序執行;
  • 主上有一個log dump線程,用來和從的I/O線程傳遞binlog;
  • 從上有兩個線程,其中I/O線程用來同步主的binlog並生成relaylog,另外一個SQL線程用來把relaylog裏面的sql語句落地;

MySQL主從配置

準備工作

1. 準備AB兩臺機器都安裝好mysql,mysql安裝詳情請查看如下鏈接。

https://blog.51cto.com/taoxie/2050826

配置主 (A機器)

1.修改my.cnf配置文件
[root@gary-tao mysql]# vi /etc/my.cnf

增加配置內容:

server-id=100         
log_bin=aminglinux1   

[root@gary-tao mysql]# /etc/init.d/mysqld restart  //更改完配置重啓mysql
Shutting down MySQL.... SUCCESS! 
Starting MySQL.. SUCCESS! 
[root@gary-tao mysql]# cd /data/mysql/
[root@gary-tao mysql]# ls -lt          //重啓完成後目錄下有生成新的文件
總用量 110648
-rw-rw---- 1 mysql mysql 50331648 1月  19 19:44 ib_logfile0
-rw-rw---- 1 mysql mysql 12582912 1月  19 19:44 ibdata1
-rw-rw---- 1 mysql mysql    24867 1月  19 19:44 gary-tao.err
-rw-rw---- 1 mysql mysql        6 1月  19 19:44 gary-tao.pid
-rw-rw---- 1 mysql mysql      120 1月  19 19:44 aminglinux1.000001
-rw-rw---- 1 mysql mysql       21 1月  19 19:44 aminglinux1.index
drwx------ 2 mysql mysql      324 1月  18 13:42 zrlog
drwx------ 2 mysql mysql     4096 1月  15 19:25 mysql2
-rw-rw---- 1 mysql mysql       56 12月 27 19:40 auto.cnf
drwx------ 2 mysql mysql     4096 12月 27 19:32 mysql
drwx------ 2 mysql mysql     4096 12月 27 19:32 performance_schema
-rw-rw---- 1 mysql mysql 50331648 12月 27 19:32 ib_logfile1
drwx------ 2 mysql mysql        6 12月 27 19:32 test

修改配置示例圖

MySQL主從配置

2.準備一個數據庫做演示使用
[root@gary-tao mysql]# mysqldump -uroot -pszyino-123 zrlog > /tmp/zrlog.sql    //備份之前舊的數據庫zrlog
Warning: Using a password on the command line interface can be insecure.
[root@gary-tao mysql]# du -sh /tmp/zrlog.sql   //查看數據庫大小
12K /tmp/zrlog.sql
[root@gary-tao mysql]# mysql -uroot -pszyino-123 -e "create database aming"   //創建一個新的數據庫
Warning: Using a password on the command line interface can be insecure.
[root@gary-tao mysql]# mysql -uroot -pszyino-123 aming < /tmp/zrlog.sql     //恢復之前備份的zrlog庫
Warning: Using a password on the command line interface can be insecure.
[root@gary-tao mysql]# ls -lt
總用量 225344
-rw-rw---- 1 mysql mysql 50331648 1月  19 20:45 ib_logfile0
-rw-rw---- 1 mysql mysql 79691776 1月  19 20:45 ibdata1
-rw-rw---- 1 mysql mysql    12097 1月  19 20:45 aminglinux1.000001
drwx------ 2 mysql mysql      324 1月  19 20:45 aming
-rw-rw---- 1 mysql mysql    24867 1月  19 19:44 gary-tao.err
-rw-rw---- 1 mysql mysql        6 1月  19 19:44 gary-tao.pid
-rw-rw---- 1 mysql mysql       21 1月  19 19:44 aminglinux1.index
drwx------ 2 mysql mysql      324 1月  18 13:42 zrlog
drwx------ 2 mysql mysql     4096 1月  15 19:25 mysql2
-rw-rw---- 1 mysql mysql       56 12月 27 19:40 auto.cnf
drwx------ 2 mysql mysql     4096 12月 27 19:32 mysql
drwx------ 2 mysql mysql     4096 12月 27 19:32 performance_schema
-rw-rw---- 1 mysql mysql 50331648 12月 27 19:32 ib_logfile1
drwx------ 2 mysql mysql        6 12月 27 19:32 test
3.創建用作主從相互同步數據的用戶
[root@gary-tao mysql]# mysql -uroot -pszyino-123
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 1535
Server version: 5.6.35-log MySQL Community Server (GPL)

Copyright (c) 2000, 2016, 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> grant replication slave on *.* to 'repl'@'172.16.111.110' identified by 'szyino-123';  //創建同步賬戶

#這裏的repl是爲從(slave)端設置的訪問主(master)端的用戶,也就是要完成主從複製的用戶,密碼爲szyino-123,這裏的127.16.111.110爲slave(從)的ip。
Query OK, 0 rows affected (0.00 sec)

mysql> flush tables with read lock;  //鎖定數據庫寫操作
Query OK, 0 rows affected (0.02 sec)

mysql> show master status; //查看master的狀態,這些數據是要記錄的,一會在slave端用到。
+--------------------+----------+--------------+------------------+-------------------+
| File               | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+--------------------+----------+--------------+------------------+-------------------+
| aminglinux1.000001 |    12777 |              |                  |                   |
+--------------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)

mysql> quit
Bye
[root@gary-tao mysql]# ls   //爲了更加與生產環境一樣,把所有的庫都做一個備份,包括aming\mysql2\zrlog,mysql庫不需要同步。
aming               aminglinux1.index  gary-tao.err  ibdata1      ib_logfile1  mysql2              test
aminglinux1.000001  auto.cnf           gary-tao.pid  ib_logfile0  mysql        performance_schema  zrlog
[root@gary-tao mysql]# ls /tmp/zrlog.sql 
/tmp/zrlog.sql
[root@gary-tao mysql]# mysqldump -uroot -pszyino-123 mysql2 > /tmp/my2.sql
Warning: Using a password on the command line interface can be insecure.
[root@gary-tao mysql]# ls /tmp/*sql
/tmp/my2.sql   /tmp/zrlog.sql

配置從(B機器)

1.修改slave的配置文件my.cnf
[root@gary mysql]# vi /etc/my.cnf

增加配置如下內容:

server-id=110   //設置成和master(主)不一樣的數字,若一樣會導致後面的操作不成功

[root@gary mysql]# /etc/init.d/mysqld restart //重啓MysqL
Shutting down MySQL.. SUCCESS! 
Starting MySQL.. SUCCESS! 

修改配置示例圖

MySQL主從配置

2.把主上庫同步到從上
[root@gary mysql]# scp 172.16.111.100:/tmp/*.sql /tmp/
The authenticity of host '172.16.111.100 (172.16.111.100)' can't be established.
ECDSA key fingerprint is 89:19:99:8c:63:ff:d9:e6:19:0d:81:03:27:54:49:78.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '172.16.111.100' (ECDSA) to the list of known hosts.
[email protected]'s password: 
Permission denied, please try again.
[email protected]'s password: 
my2.sql                                                                                           100%  638KB 637.7KB/s   00:00    
zrlog.sql          

[root@gary ~]# mysql -uroot
-bash: mysql: 未找到命令
[root@gary ~]# alias 'mysql=/usr/local/mysql/bin/mysql'
[root@gary ~]# alias 'mysqldump=/usr/local/mysql/bin/mysqldump'
[root@gary ~]# mysql -uroot
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.6.35 MySQL Community Server (GPL)

Copyright (c) 2000, 2016, 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 aming;
Query OK, 1 row affected (0.00 sec)

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

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

mysql> quit
Bye
3.恢復數據
[root@gary mysql]# mysql -uroot zrlog < /tmp/zrlog.sql 
[root@gary mysql]# mysql -uroot aming < /tmp/zrlog.sql 
[root@gary mysql]# mysql -uroot mysql2 < /tmp/my2.sql 
4.實現主從
[root@gary mysql]# mysql -uroot
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 5
Server version: 5.6.35 MySQL Community Server (GPL)

Copyright (c) 2000, 2016, 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> stop slave;
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> change master to master_host='172.16.111.100', master_user='repl', master_password='szyino-123', master_log_file='aminglinux1.000001', master_log_pos=12777;
Query OK, 0 rows affected, 2 warnings (0.02 sec)

#解釋說明:
change master這個命令是一條,打完逗號後可以按回車,直到你打分號纔算結束,其中,master_log_file和master_log_pos是在前面使用show master status命令查到的數據。

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: 172.16.111.100
                  Master_User: repl
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: aminglinux1.000001
          Read_Master_Log_Pos: 12777
               Relay_Log_File: gary-relay-bin.000002
                Relay_Log_Pos: 285
        Relay_Master_Log_File: aminglinux1.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: 12777
              Relay_Log_Space: 457
              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: 100
                  Master_UUID: ccffc787-eafa-11e7-9474-000c2909e558
             Master_Info_File: /data/mysql/master.info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: Slave has read all relay log; waiting for the slave I/O thread to update it
           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
1 row in set (0.00 sec)

#解釋說明:

看是否有,兩個Yes說明配置成功。
 Slave_IO_Running: Yes
 Slave_SQL_Running: Yes
 還需關注
 Seconds_Behind_Master: 0  //爲主從延遲的時間
 Last_IO_Errno: 0
 Last_IO_Error:
 Last_SQL_Errno: 0
 Last_SQL_Error:
 如果主從不正常了,需要看這裏的error信息。

配置成功示例圖:

MySQL主從配置

5.到主上機器開啓數據庫寫操作
[root@gary-tao mysql]# mysql -uroot -pszyino-123
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 2407
Server version: 5.6.35-log MySQL Community Server (GPL)

Copyright (c) 2000, 2016, 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> unlock tables;  //執行開啓數據寫操作命令
Query OK, 0 rows affected (0.00 sec)

測試主從同步

1.說明幾個配置參數
主服務器上,這兩個參數用一個就可以了。

binlog-do-db=       //定義需要同步指定的庫,多個庫用英文的逗號分隔。
binlog-ignore-db=   //定義不需要同步的庫。

從服務器上

replicate_do_db=      //定義需要同步指定的庫,多個庫用英文的逗號分隔
replicate_ignore_db=  //定義不需要同步的庫。
replicate_do_table=   //定義需要同步的表
replicate_ignore_table=  //定義不需要同步的表
replicate_wild_do_table=   //如aming庫.%, 支持通配符%(主要使用)
replicate_wild_ignore_table=
2.測試主從同步
[root@gary-tao mysql]# mysql -uroot -pszyino-123  
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 2407
Server version: 5.6.35-log MySQL Community Server (GPL)

Copyright (c) 2000, 2016, 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> unlock tables;
Query OK, 0 rows affected (0.00 sec)

mysql> use aming;
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> show tables;
+-----------------+
| Tables_in_aming |
+-----------------+
| comment         |
| link            |
| log             |
| lognav          |
| plugin          |
| tag             |
| type            |
| user            |
| website         |
+-----------------+
9 rows in set (0.00 sec)

//進入主上查看website錶行數
mysql> select count(*) website;  
+---------+
| website |
+---------+
|       1 |
+---------+
1 row in set (0.00 sec)

mysql> truncate table website;
Query OK, 0 rows affected (0.03 sec)

//進入從上查看user錶行數
mysql> use aming;
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 count(*) website;
+---------+
| website |
+---------+
|       1 |
+---------+
1 row in set (0.00 sec)

//清空主上的website表內容
mysql> truncate table website;
Query OK, 0 rows affected (0.03 sec)

//再次查看主上wedsite表雖然顯示一行,但是內容已爲空。
mysql> select count(*) website;
+---------+
| website |
+---------+
|       1 |
+---------+
1 row in set (0.00 sec)

mysql> select * from website;
Empty set (0.00 sec)

//查看從上的wedsite內容已爲空。
mysql> select count(*) from website;
+----------+
| count(*) |
+----------+
|        0 |
+----------+
1 row in set (0.00 sec)

//在主上刪除website這個表
mysql> drop table website;
Query OK, 0 rows affected (0.02 sec)

//在從上查看websitep這個表已被刪除
mysql> select * from webiste;
ERROR 1146 (42S02): Table 'aming.webiste' doesn't exist

注意:如果不小心在從上刪除了表,你再次打開查看主從配置時,發現報錯了,如下:

mysql> show slave status\G
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 172.16.111.100
                  Master_User: repl
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: aminglinux1.000001
          Read_Master_Log_Pos: 12997
               Relay_Log_File: gary-relay-bin.000002
                Relay_Log_Pos: 383
        Relay_Master_Log_File: aminglinux1.000001
             Slave_IO_Running: Yes
            Slave_SQL_Running: No   //這裏變NO了
              Replicate_Do_DB: 
          Replicate_Ignore_DB: 
           Replicate_Do_Table: 
       Replicate_Ignore_Table: 
      Replicate_Wild_Do_Table: 
  Replicate_Wild_Ignore_Table: 
                   Last_Errno: 1051
                   Last_Error: Error 'Unknown table 'aming.website'' on query. Default database: 'aming'. Query: 'DROP TABLE `website` /* generated by server */'
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 12875
              Relay_Log_Space: 677
              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: NULL
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error: 
               Last_SQL_Errno: 1051
               Last_SQL_Error: Error 'Unknown table 'aming.website'' on query. Default database: 'aming'. Query: 'DROP TABLE `website` /* generated by server */'
  Replicate_Ignore_Server_Ids: 
             Master_Server_Id: 100
                  Master_UUID: ccffc787-eafa-11e7-9474-000c2909e558
             Master_Info_File: /data/mysql/master.info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: 
           Master_Retry_Count: 86400
                  Master_Bind: 
      Last_IO_Error_Timestamp: 
     Last_SQL_Error_Timestamp: 180123 15:28:37
               Master_SSL_Crl: 
           Master_SSL_Crlpath: 
           Retrieved_Gtid_Set: 
            Executed_Gtid_Set: 
                Auto_Position: 0
1 row in set (0.00 sec)

如果出現了這個情況只能重新做主從:

主上操作查看master:

mysql> show master status;
+--------------------+----------+--------------+------------------+-------------------+
| File               | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+--------------------+----------+--------------+------------------+-------------------+
| aminglinux1.000001 |    12997 |              |                  |                   |
+--------------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)

從上配置change master重做主從(爲什麼可以直接做主從,因爲數據還是一致的,沒有做其它的操作)

mysql> stop slave;
Query OK, 0 rows affected (0.01 sec)

//除了最後面數字需要更改,其它參數都一樣。
mysql> change master to master_host='172.16.111.100', master_user='repl', master_password='szyino-123', master_log_file='aminglinux1.000001', master_log_pos=12997;
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: 172.16.111.100
                  Master_User: repl
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: aminglinux1.000001
          Read_Master_Log_Pos: 12997
               Relay_Log_File: gary-relay-bin.000002
                Relay_Log_Pos: 285
        Relay_Master_Log_File: aminglinux1.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: 12997
              Relay_Log_Space: 457
              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: 100
                  Master_UUID: ccffc787-eafa-11e7-9474-000c2909e558
             Master_Info_File: /data/mysql/master.info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: Slave has read all relay log; waiting for the slave I/O thread to update it
           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
1 row in set (0.00 sec)
備註:如果在數據不一致的情況下,需要重新同步數據,然後在做change master操作。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章