MySQL主從複製

 

1、要求mysql

一、配置現有的一臺MySQL服務器爲主服務器,另外一臺做爲其從服務器sql

二、其中Master服務器容許查詢和寫入,Slave只容許查詢數據庫

 

2、方案vim

使用3RHEL6.5虛擬機,以下圖所示。其中192.168.4.10MySQL主服務器,負責提供同步源;192.168.4.20MySQL從服務器,通過調取主服務器上的binlog日誌,在本地重作對應的庫、表,實現與主服務器的同步;192.168.4.100是客戶機,用來登陸數據庫驗證試驗結果,也能夠不用客戶機而直接在從和主上操做數據庫。服務器

wKiom1QZp5Cz6t7YAAE9f1Tc1s4120.jpg

 

3、實現網絡

1、準備工做socket

爲兩臺MySQL服務器安裝MySQL-serverMySQL-client軟件包併爲數據庫修改root密碼,客戶機上只需安裝MySQL-client。這裏用的軟件包包含在了 MySQL-5.6.15-1.el6.x86_64.rpm-bundle.tar裏(點擊可下載)ide

若是是兩臺服務器是克隆的,那麼它們mysql服務器的server-uuid值可能相同,能夠用下面兩條命令查看一下工具

[root@slave ~]# cat /var/lib/mysql/auto.cnf測試

[auto]

server-uuid=c8b982e3-336b-11e4-9780-525400f9a647

要是相同,能夠用uuidgen從新生成一個uuid,以替換auto.cnf裏的server-uuid

[root@client ~]# uuidgen 

bad15423-2ec5-4204-85b5-8d4027e05408

[root@master ~]# cat /var/lib/mysql/auto.cnf 

[auto]

server-uuid=bad15423-2ec5-4204-85b5-8d4027e05408

    

修改配置文件並重啓mysql服務以啓用binlog日誌

[root@master ~]# vim /etc/my.cnf 

... ...

log-bin=mysql-bin

[root@master ~]# service mysql restart

Shutting down MySQL....                                  [肯定]

Starting MySQL....                                      [肯定]

 

master上建立grade庫來假設主服務器上已有的數據

[root@master ~]# mysql -uroot -p

Enter password:                    //root身份登陸,輸入root用戶密碼

... ...

mysql> create database grade;

Query OK, 1 row affected (0.00 sec)

 

mysql> create table grade.math ( name varchar(20),score float(4,1));

Query OK, 0 rows affected (1.36 sec)

mysql> insert into grade.math values ( "jim" ,80.5);

Query OK, 1 row affected (0.17 sec)

mysql> select * from grade.math;

+------+-------+

| name | score |

+------+-------+

| jim  |  80.5 |

+------+-------+

1 row in set (0.00 sec)

 

2、配置主服務器master (192.168.4.10)

1)修改配置文件/etc/my.cnf,指定服務器ID號、容許日誌同步,重啓mysql服務

[root@master mysql]# cat /etc/my.cnf 

[mysqld]

datadir=/var/lib/mysql     //數據庫主目錄

socket=/var/lib/mysql/mysql.sock

user=mysql

server_id=10          //指定服務器ID

log-bin=mysql-bin      //啓用binlog日誌並指定前綴

sync-binlog=1         //容許日誌同步

... ...

[root@master mysql]# service mysql restart

Shutting down MySQL..                                      [肯定]

Starting MySQL.                                            [肯定]

 

2)新建一個備份用戶,授予複製權限,容許其從slave服務器訪問

mysql> GRANT REPLICATION SLAVE ON *.* TO 'replicater'@'192.168.4.%' IDENTIFIED BY 'pwd123';

Query OK, 0 rows affected (0.07 sec)

 

3)檢查master服務器的同步狀態

mysql> SHOW MASTER STATUS\G;

*************************** 1. row ***************************

             File: mysql-bin.000002     //當前的日誌文件名

         Position: 334                 //當前記錄的位置

     Binlog_Do_DB: 

 Binlog_Ignore_DB: 

Executed_Gtid_Set: 

1 row in set (0.00 sec)

 

3、配置從服務器slave192.168.4.20

1)修改配置文件/etc/my.cnf,指定服務器ID號,重啓mysql服務。在生產環境中還能夠根據更MySQL手冊設置更詳細的選項。

[root@slave mysql]# vim /etc/my.cnf

[mysqld]

datadir=/var/lib/mysql

socket=/var/lib/mysql/mysql.sock

user=mysql

server_id=20                    

log-bin=slave     //啓用binlog日誌並指定前綴

... ...

 

[root@slave mysql]# service mysql restart

Shutting down MySQL..                                      [肯定]

Starting MySQL.                                            [肯定]

 

2)登陸mysql,發起同步

經過CHANGE MASTER語句指定MASTER服務器的IP地址、同步用戶名/密碼、起始日誌文件、偏移位置

 

mysql> CHANGE MASTER TO MASTER_HOST='192.168.4.10',

    -> MASTER_USER='replicater',

    -> MASTER_PASSWORD='pwd123',

    -> MASTER_LOG_FILE='mysql-bin.000001', //對應Master的日誌文件

    -> MASTER_LOG_POS=1;   ////對應Master的日誌偏移位置

若是起始日誌文件、偏移位置按照上面的寫法,那麼能夠同步主服務器上自啓用binlog日誌以來對數據庫所作的操做。

也能夠在主服務器上SHOW MASTER STATUS\G; 按照當前狀態填寫,這時只同步master從這一刻之後對數據庫的操做,之前的庫和表不會同步,能夠選擇手動同步。當現有庫、表都採用MyISAM引擎時,可執行離線導入導出,這樣更有效率。不然可以使用mysqldump等工具來實現 庫的導入導出。

 

而後啓動slave

mysql> START SLAVE;

Query OK, 0 rows affected (0.05 sec)

一旦啓用SLAVE複製,當須要修改MASTER信息時,應先執行STOP SLAVE中止複製,而後從新修改、啓動複製。

 

經過上述鏈接操做,MASTER服務器的設置信息自動存爲master.info文件,之後每次MySQL服務程序時會自動調用並更新,無需重複設置。查看master.info文件的開頭部份內容,可驗證相關設置:

[root@slave mysql]# head /var/lib/mysql/master.info 

23

mysql-bin.000001     //對應Master的日誌文件 

120                 

192.168.4.10          //masterip地址

replicater               //master同步的用戶名  

pwd123                //密碼

3306                   //端口

60

0

 

 

mysql> SHOW SLAVE STATUS\G;

*************************** 1. row ***************************

               Slave_IO_State: Waiting for master to send event

                  Master_Host: 192.168.4.10

                  Master_User: replicater

                  Master_Port: 3306

                Connect_Retry: 60

              Master_Log_File: mysql-bin.000002

          Read_Master_Log_Pos: 334

               Relay_Log_File: slave-relay-bin.000003

                Relay_Log_Pos: 497

        Relay_Master_Log_File: mysql-bin.000002

             Slave_IO_Running: Yes     //IO線程應該已運行

            Slave_SQL_Running: Yes     //SQL線程應該已運行

              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: 334

              Relay_Log_Space: 1283

              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: bad15423-2ec5-4204-85b5-8d4027e05408

             Master_Info_File: /var/lib/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)

 

 

START SLAVE直接報錯失敗,請檢查CHANGE MASTER相關設置是否有誤,糾正後再重試;若IO線程或SQL線程有一個爲「No」,則應檢查服務器的錯誤日誌,分析並排除故障後重啓主從複製。

 

4測試主從同步效果

在主服務器上受權一個用戶,會自動同步到slave上,用戶用於在客戶端(192.168.4.100)登陸:

mysql> GRANT ALL ON grade.* TO "user01"@"192.168.4.%" IDENTIFIED BY "pwd123" ;

Query OK, 0 rows affected (0.12 sec)

 

在客戶端上登陸從庫

在從上發現grade庫已經同步過來

[root@client ~]# mysql -h192.168.4.20 -uuser01 -ppwd123

mysql> SHOW DATABASES;

+--------------------+

| Database           |

+--------------------+

| information_schema |

| grade              |

| test               |

+--------------------+

3 rows in set (0.00 sec)

 

mysql> SELECT * FROM grade.math;

+------+-------+

| name | score |

+------+-------+

| jim  |  80.5 |

+------+-------+

1 row in set (0.00 sec)

 

1在客戶端用user01登陸Master數據庫

 

grade庫的math表裏隨意插入幾條表記錄:

[root@client 桌面]# mysql -h 192.168.4.10 -uuser01 -ppwd123

... ...

mysql> INSERT INTO grade.math VALUES ("tom",78),("lily",90);

Query OK, 2 rows affected (0.25 sec)

Records: 2  Duplicates: 0  Warnings: 0

 

mysql> SELECT * FROM grade.math;

+------+-------+

| name | score |

+------+-------+

| jim  |  80.5 |

| tom   |  78.0 |

| lily |  90.0 |

+------+-------+

3 rows in set (0.00 sec)

 

2)在Slave上確認自動同步的結果

直接查詢math表的記錄,應該與Master上的同樣,這才說明主從同步已經成功生效:

[root@client 桌面]# mysql -h 192.168.4.20 -uuser01 -ppwd123

... ...

mysql> SELECT * FROM grade.math;

+------+-------+

| name | score |

+------+-------+

| jim    |  80.5  |

| tom   |  78.0  |

| lily    |  90.0  |

+------+-------+

3 rows in set (0.00 sec)

 

3)在Master服務器上可查看Slave主機的信息

mysql> SHOW SLAVE HOSTS;

+-----------+------+------+-----------+--------------------------------------+

| Server_id | Host | Port | Master_id | Slave_UUID                           |

+-----------+------+------+-----------+--------------------------------------+

|        20 |      | 3306 |        10 | c8b982e3-336b-11e4-9780-525400f9a647 |

+-----------+------+------+-----------+--------------------------------------+

1 row in set (0.00 sec)

 

五、將slave服務器設爲只讀

通常來講,爲了不寫入衝突,採用主、從複製結構時,不該該容許用戶從Slave執行數據庫寫入操做,這樣會致使雙方數據的不一致性。

正由於如此,咱們能夠把Slave數據庫限制爲只讀模式,這種狀況下有SUPER權限的用戶和SLAVE同步線程才能寫入。相關驗證操做及效果可參考如下過程。

1)未啓用只讀前,驗證從slave寫入

在客戶端上以user01身份登陸slave,並寫入數據:

[root@client 桌面]# mysql -h 192.168.4.20 -uuser01 -ppwd123

... ...

mysql> INSERT INTO grade.math VALUES ("bob",60);

Query OK, 1 row affected (0.09 sec)

 

slave上能夠看到新插入的數據:

mysql> SELECT * FROM grade.math;

+------+-------+

| name | score |

+------+-------+

| jim  |  80.5 |

| tom  |  78.0 |

| lily |  90.0 |

| bob  |  60.0 |

+------+-------+

4 rows in set (0.00 sec)

mysql> QUIT

Bye

 

可是在master上卻看不到,致使主、從上的math表數據不一致

[root@client 桌面]# mysql -h 192.168.4.10 -uuser01 -ppwd123

... ...

mysql> SELECT * FROM grade.math;

+------+-------+

| name | score |

+------+-------+

| jim  |  80.5 |

| tom  |  78.0 |

| lily |  90.0 |

+------+-------+

3 rows in set (0.00 sec)

mysql> quit

Bye

 

完成上述驗證後,在slave上刪除剛剛插入的記錄,確保主從數據一致

[root@client 桌面]# mysql -h 192.168.4.20 -uuser01 -ppwd123

... ...

mysql> DELETE FROM grade.math WHERE name="bob";

Query OK, 1 row affected (0.11 sec)

 

mysql> SELECT * FROM grade.math;

+------+-------+

| name | score |

+------+-------+

| jim    |  80.5 |

| tom   |  78.0 |

| lily     |  90.0 |

+------+-------+

3 rows in set (0.00 sec)

 

mysql> QUIT

Bye

 

2)修改slave/etc/my.cnf文件,重啓mysql服務

[root@slave mysql]# vim /etc/my.cnf 

[mysqld]

... ...

read_only=1             //啓動只讀模式

[root@slave mysql]# service mysql restart

Shutting down MySQL..                                    [肯定]

Starting MySQL..                                          [肯定]

3)再次在slave上驗證數據庫寫入操做

client192.168.4.100)上以user01用戶登陸從庫

[root@client 桌面]# mysql -h 192.168.4.20 -uuser01 -ppwd123

... ...

mysql> USE grade;                //切換到grade庫,

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> INSERT INTO math VALUES ("lucy",99);   

ERROR 1290 (HY000): The MySQL server is running with the --read-only option so it cannot execute this statement       //表的寫操做失敗,提示數據庫運行在只讀模式下

 

4、擴展

指定哪些庫參與主從複製

有兩種途徑:

Master上限制,採用binlog-do-dbbinlog-ignore-db選項,指定對哪些庫記錄或不記錄二進制日誌,不記錄的天然就沒法被Slave讀取,從而也就至關於不參與同步。

Slave上限制,採用replicate-do-dbreplicate-ignore-db選項,指定對哪些庫執行復制或排除複製。

上述設置參數中,記錄與不記錄屬於互斥選項,不要同時設置;複製與不復制也是互斥選項,不要同時設置。

當設置多條replicate-do-dbreplicate-ignore-db時,須要特別注意:這種狀況下Master的跨庫操做(好比UPDATE 庫名.表名 .. ..)不會被同步,從而易致使後續同步報錯中斷。要解決這個問題,可改用(或合用)如下兩個選項:

    replicate-wild-do-table=庫名.%

    replicate-wild-ignore-table=庫名.%

 

以只同步test庫爲例,相關操做及效果參考以下:

1)在slave上修改/etc/my.cnf文件,只同步test

[root@slave mysql]# vim /etc/my.cnf 

[mysqld]

... ...

replicate-do-db=mysql            //同步mysql庫

replicate-wild-do-table=mysql.%     //含跨庫更新,可是跨的庫只容許在能夠同步的庫列表裏,好比在這裏只容許在test庫或mysql庫裏更新mysql庫

replicate_do_db=test           

replicate_wild_do_table=test.%   

//其餘未指定的庫將被忽

... ...

[root@slave mysql]# service mysql restart

Shutting down MySQL....                                    [肯定]

Starting MySQL..                                           [肯定]

 

2)在master上分別操做test庫、grade

test庫中新建t1

mysql> USE mysql;

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> CREATE TABLE test.t1(id int(4),name varchar(20));

Query OK, 0 rows affected (0.93 sec)

 

mysql> INSERT INTO test.t1 VALUES(1,"mike");

Query OK, 1 row affected (0.17 sec)

 

mysql> SELECT * FROM test.t1;

+------+------+

| id   | name |

+------+------+

|    1 | mike |

+------+------+

1 row in set (0.00 sec)

 

grade中新建English表:

mysql> CREATE TABLE grade.English (name varchar(20),score float(3,1));

Query OK, 0 rows affected (1.15 sec)

mysql> INSERT INTO grade.English VALUES ("harry",60);

Query OK, 1 row affected (0.17 sec)

mysql> SELECT * FROM grade.English;

+-------+-------+

| name  | score |

+-------+-------+

| harry |  60.0 |

+-------+-------+

1 row in set (0.00 sec)

 

3)在slave上觀察同步結果

Master上對test庫的操做已經同步到slave

mysql> SELECT * FROM test.t1;

+------+------+

| id     | name |

+------+------+

|    1   | mike |

+------+------+

1 row in set (0.00 sec)

 

Master上對grade庫的操做被slave忽略

mysql> SELECT * FROM grade.English;

ERROR 1146 (42S02): Table 'grade.English' doesn't exist

 

5、/etc/my.cnf經常使用的配置選項

適用於Master服務器:

binlog-do-db=name 設置Master對那些庫記日誌

binlog-ignore-db=name 設置Master對那些庫不記日誌

 

適用於Slave服務器:

log-slave-updates 記錄從庫更新,容許鏈式複製(A-B-C

relay-log=slave1-relay-bin  指定中繼日誌文件名

replicate-do-db=mysql  僅複製指定庫,其餘庫將被忽略,此選項可設置多條(省略時複製全部庫)

replicate-ignore-db=test 不復制哪些庫,其餘庫將被忽略(與上一條do-db衝突,只需選用其中一條)

report-host=slave1    報告給Master的主機名或IP地址

slave-net-timeout=60 出現網絡中斷時,重試超時(默認爲60秒)

相關文章
相關標籤/搜索