一、測試環境:
主庫(Master):Centos 5.5 64位操作系統
Mysql Server version: 5.1.59
IP:192.168.1.188
從庫(Slave):Centos 5.5 64位操作系統
Mysql Server version: 5.1.59
IP:192.168.1.189
權限管理:GRANT privileges ON db TO user@host IDENTIFIED BY "password" WITH GRANT OPTION
Privileges==alter 、select、create、 delect、 drop 、index、 insert 、replication slave 等
常見問題:Slave_IO_Running: No
1.先檢查防火牆設置(測試前最好關閉)
2.所有操作完後,注意要重啓mysql服務
二、主庫的操作
#vi /etc/my.cnf
server-id
= 1
my.cnf內容比較多,這裏只介紹一些重要參數
server-id = 1
這是數據庫ID,此ID唯一,主庫用默認的1即可,從庫調整爲2,多個從庫的ID依次類推,切不可有相同ID出現,這樣會造成同步出錯。
log-bin=mysql-bin 二進制日誌文件,此項必須啓用,從庫需要通過它進行數據同步。
配置主庫其實就檢查這2個選項,如果你同步的數據庫不是全部的,只是同步個別庫,或個別的不需要同步,需要繼續往下看
binlog-do-db=test 需要同步的數據庫,如果同步多個庫,需要另行重寫,如
binlog-do-db=test1
binlog-do-db=test2
(數據庫安裝包不同這個選項有的配置文件裏沒有,需要加上)
binlog-ignore-db=mysql
不需要同步的數據庫,與binlog-do-db正好相反,如果你有100個庫,只想同步其中幾個,那麼你應該使用binlog-do-db,如果不想同步其中的幾個,就使用binlog-ignore-db
(數據庫安裝包不同這個選項有的配置文件裏沒有,需要加上)
建立同步用的數據庫賬戶
主庫必須提供一個賬戶讓從庫通過此賬戶進行連接並進行同步,進入mysql後輸入下面命令
mysql> grant replication slave on *.* to [email protected] identified by '123456';
鎖住主庫表,停止數據更新
Mysql> flush tables with read lock;
打開另一個shell窗口
Shell> cd /var/lib/
Shell> tar -zcvf mysqlbak.tar.gz mysql
(另外一種打包數據庫的方法: Shell> mysqldump --opt --default-character-set=utf8 --master-data --databases castlot warlog assist > castlot120116.sql
Shell>vim castlot120116.sql 查看File和Position並記錄)
Mysql>show master status;
+------------------+----------+--------------+------------------+
|
File
| Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000073
|
98
|
|
|
+------------------+----------+--------------+------------------+
1 row in set (0.00 sec)
Mysql> unlock tables;
將mysqlbak.tar.gz拷貝到叢庫數據庫目錄下並解壓
Shell>scp mysqlbak.tar.gz [email protected]:/usr/local/
三、從庫的操作
Shell>cd /usr/local
Shell>tar -zxvf mysqlbak.tar.gz
(另一種對應方法:Shell>mysql -S /tmp/mysql.sock --default-character-set=utf8 < castlot120116.sql)
將叢庫my.cnf中server-id=1修改爲server-id=2
增加要同步的數據庫:
replicate-wild-do-table=assist.%
replicate-wild-do-table=castlot.%
replicate-wild-do-table=warlog.%
重啓下mysql
之前先stop slave
設置連接MASTER MASTER_LOG_FILE爲主庫的File:mysql-bin.000073,MASTER_LOG_POS爲主庫的Position:98
mysql> change master to
master_host='192.168.1.188',
master_user='syncuser',
master_password='123456',
master_log_file='mysql-bin.000073',
master_log_pos=98;
Mysql> start slave;
檢查從庫是否正常同步
mysql>show slave status \G;
*************************** 1. row
***************************
Slave_IO_State: Waiting for master to send event
Master_Host: 192.168.1.188
Master_User: syncuser
Master_Port: 3306
Connect_Retry: 60
Master_Log_File: mysql-bin.000073
Read_Master_Log_Pos: 98
Relay_Log_File: TMac-relay-bin.000073
Relay_Log_Pos: 12753
Relay_Master_Log_File: mysql-bin.000073
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: