一、環境描述
主數據庫服務器ip:192.168.0.2
從數據庫服務器ip:192.168.0.3
主從服務器上的mysql已全新安裝,但並為投入生產,所以無數據產生。
二、主從復制配置
1.主數據庫服務器master配置
(1)為從服務器slave授權
mysql> grant replication slave on *.* to slave@192.168.0.3 identified by “123”;
(2)查看master狀態
mysql> show master status;
+——————+———-+————–+——————+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+——————+———-+————–+——————+
| mysql-bin.000003 | 400 | | |
+——————+———-+————–+——————+
1 row in set (0.00 sec)
記下file和position,一會配置slave會用到。(file為mysql日志的文件,position為日志的線索號,從服務器將從這麼位置開始復制)
2.從數據庫服務器slave配置
(1)修改slave的server id,避免和其他mysql數據庫的重復
vi /etc/my.cnf
server-id = 2
(2)執行sql語句的同步
mysql> change master to master_host=192.168.0.2, master_user=slave, master_password=123, master_log_file=mysql-bin.000003, master_log_pos=400;
(3)啟動slave的同步功能
mysql> start slave;
(4)查看slave狀態
mysql> show slave status G;
*************************** 1. row ***************************
Slave_IO_State: Waiting for master to send event
Master_Host: 192.168.0.2
Master_User: slave
Master_Port: 3306
Connect_Retry: 60
Master_Log_File: mysql-bin.000003
Read_Master_Log_Pos: 548
Relay_Log_File: mysql-relay-bin.000002
Relay_Log_Pos: 399
Relay_Master_Log_File: mysql-bin.000003
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: 548
Relay_Log_Space: 554
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:
1 row in set (0.02 sec)
ERROR:
No query specified
註:Slave_IO_Running: Yes
Slave_SQL_Running: Yes當IO和SQL這兩個進程都是Yes,master和slave就可以進行主從復制瞭。
三、驗證測試
1.在master上創建一個測試表(root用戶)
mysql> use test
mysql> create table tbs (id int);
mysql> insert into tbs values(1);
2.在slave上查看是否復制成功(root用戶)
mysql> use test
mysql> show tables;
mysql> select * from tbs;
+——+
| id |
+——+
| 1 |
+——+
1 row in set (0.00 sec)
顯示復制成功!