劉瑾葦
2017-01-08
最終答案
1、首先要在本地建立兩個(gè)mysql服務(wù)(參考這里),指定不同的端口。我這里一個(gè)主(3306),一個(gè)從(3307)。2、然后修改主配置文件:[mysqld]server-id = 1 binlog-do-db=test #要同步的數(shù)據(jù)庫(kù)#binlog-ignore-db=mysql #不同步的數(shù)據(jù)庫(kù),如果指定了binlog-do-db這里應(yīng)該可以不用指定的log-bin=mysql-bin #要生成的二進(jìn)制日記文件名稱修改從配置文件:[mysqld]server-id = 2log-bin = mysql-binreplicate-do-db=test3、在主庫(kù)添加一個(gè)用戶 repl 并指定replication權(quán)限create user 'repl'@'127.0.0.1' identified by 'asdf';GRANT REPLICATION SLAVE ON *.* TO 'repl'@'127.0.0.1'; -- --這里我指定數(shù)據(jù)庫(kù)(test.*)時(shí)報(bào)錯(cuò),而指定全庫(kù)(*.*)時(shí)會(huì)成功。4、保持主從mysql的test數(shù)據(jù)庫(kù)初始狀態(tài)一致。一般是先將所有的表加讀鎖,然后copy磁盤(pán)上的數(shù)據(jù)庫(kù)文件夾。我這里直接停止服務(wù),然后將數(shù)據(jù)文件拷貝過(guò)去。5、在主數(shù)據(jù)庫(kù)里面運(yùn)行show master status;記下file和position字段對(duì)應(yīng)的參數(shù)。mysql> show master status;+------------------+----------+--------------+------------------+| File | Position | Binlog_Do_DB | Binlog_Ignore_DB |+------------------+----------+--------------+------------------+| mysql-bin.000001 | 107 | test | |+------------------+----------+--------------+------------------+1 row in set (0.00 sec)6、在從庫(kù)設(shè)置它的master:mysql> change master to master_host='127.0.0.1',master_port=3306,master_user='repl',master_password='asdf',master_log_file='mysql-bin.000001',master_log_pos=107;Query OK, 0 rows affected (0.19 sec)這里的master_log_file和master_log_pos對(duì)應(yīng)剛才show master status記下的參數(shù)。7、在從庫(kù)開(kāi)啟從數(shù)據(jù)庫(kù)復(fù)制功能。slave start;mysql> slave start;Query OK, 0 rows affected (0.00 sec)在訂鼎斥刮儷鈣籌水船驚從庫(kù)可以通過(guò)show slave status來(lái)查看一些參數(shù)。8. 此時(shí)在主庫(kù)創(chuàng)建表或插入數(shù)據(jù),在從庫(kù)就會(huì)很快也能看到了。-- 主庫(kù)mysql> create table tianyc_02(b int);Query OK, 0 rows affected (0.16 sec)mysql> insert into tianyc_02 values(2013);Query OK, 1 row affected (0.13 sec)-- 從庫(kù)mysql> show tables;+----------------+| Tables_in_test |+----------------+| tianyc_01 || tianyc_02 |+----------------+2 rows in set (0.00 sec)mysql> select * from tianyc_02;+------+| b |+------+| 2013 |+------+1 row in set (0.00 sec)同理,可以搭建第二、第三個(gè)從節(jié)點(diǎn)。備注:兩個(gè)服務(wù)的serve_id必須不同,否則在開(kāi)啟復(fù)制功能時(shí)會(huì)提示錯(cuò)誤mysql> slave start;ERROR 1200 (HY000): The server is not configured as slave; fix in config file or with CHANGE MASTER TO