mysql主從復(fù)制运杭,不停庫
1.實(shí)現(xiàn)思路
首先通過mysqldump將主庫數(shù)據(jù)備份讲冠,然后將備份數(shù)據(jù)恢復(fù)至從庫券膀,
再在從庫中通過binlog執(zhí)行同步。
2.操作過程
MySQL主從是基于binlog日志谷扣,所以在安裝好數(shù)據(jù)庫后就要開啟binlog土全。這樣好處是,一方面可以用binlog恢復(fù)數(shù)據(jù)庫会涎,另一方面可以為主從做準(zhǔn)備裹匙。
(1)主庫配置
#vi my.cnf
server-id=1#id要唯一
log-bin=mysql-bin#開啟binlog日志
auto-increment-increment=1#在MySQL5.5以后已經(jīng)默認(rèn)是1
auto-increment-offset=1#表示自增長(zhǎng)字段從那個(gè)數(shù)開始,他的取值范圍是1 .. 65535
slave-skip-errors=all#跳過主從復(fù)制出現(xiàn)的錯(cuò)誤
(2)主庫創(chuàng)建同步賬號(hào)
mysql> create user 'slave'@'%' identified by '1234567'; ----創(chuàng)建從服務(wù)器同步用的mysql用戶
mysql> grant replication slave,replication client on *.* to 'slave'@'%'; ----授權(quán)創(chuàng)建的用戶權(quán)限
(3)從庫配置
#vi my.cnf
server-id=2
log-bin=mysql-bin#開啟binlog日志
auto-increment-increment=1#MySQL5.5以后都已經(jīng)默認(rèn)是1
auto-increment-offset=1
slave-skip-errors=all#跳過主從復(fù)制出現(xiàn)的錯(cuò)誤
read_only=1#普通用戶只讀
super_read_only=1 #root用戶只讀
(4)備份主庫
mysqldump -uroot -p123 --routines --single_transaction --master-data=2 --databases 數(shù)據(jù)庫1 數(shù)據(jù)庫2 > db.sql參數(shù)說明:
--routines:導(dǎo)出存儲(chǔ)過程和函數(shù)
--single_transaction:導(dǎo)出開始時(shí)設(shè)置事務(wù)隔離狀態(tài)末秃,并使用一致性快照開始事務(wù)概页,然后unlock tables;而lock-tables是鎖住一張表不能寫操作,直到dump完畢练慕。
--master-data:默認(rèn)等于1惰匙,將dump起始(change master to)binlog點(diǎn)和pos值寫到結(jié)果中,等于2是將change master to寫到結(jié)果中并注釋铃将。
(5)備份還原至從庫
mysql -uroot -p123 -e'create database dbname;'
mysql -uroot -p123 dbname < db.sql
(6)開啟同步
#在備份文件weibo.sql查看binlog和pos值
less db.sql
#執(zhí)行同步
#連接mysql執(zhí)行以下:
mysql -uroot -p123
change master to master_host='192.168.8.X',master_user='slave',master_password='123456',master_log_file='mysql-bin.000024',master_log_pos=507828577;
start slave; #開啟slave
show slave status \G;
#可以看到IO和SQL線程均為YES项鬼,說明主從配置成功。
Slave_IO_Running: Yes
Slave_SQL_Running: Yes