MYSQL5.6 主從復(fù)制
1.主服務(wù)器配置
1) 登陸mysql數(shù)據(jù)庫
#?mysql?-hlocalhost?-uroot?-proot?test
2) 給從服務(wù)器設(shè)置授權(quán)用戶
#?mysql>grant?replication?slave?on?*.*??to?user1@192.168.84.138?identified?by?'user1'; 或者 #?mysql>grant?all?on?*.*?to?user1@192.168.84.138?identified?by?'user1';
3) 修改主數(shù)據(jù)庫服務(wù)器的配置文件my.cnf,開啟binlog,設(shè)置server-id的值
#?vim?/etc/my.cnf ????log-bin=mysql-bin ????server-id=1
4) 在主服務(wù)器設(shè)置鎖定有效,確保沒有數(shù)據(jù)庫操作,以便獲得一個一致性的快照:(選做)
#?mysql>flush?tables?with?read?lock;
5) 目前主數(shù)據(jù)服務(wù)器已經(jīng)停止了更新操作,生成主數(shù)據(jù)庫的備份,有兩種方式:
(1)?cp全部的數(shù)據(jù) (2)?mysqldump備份數(shù)據(jù)方法 #?mysqldump?-uroot?-proot?test?-l?-F?>/tmp/test.sql? -F?即?flush?logs -l?即?讀鎖 #?cat?/tmp/test.sql? #?scp?/tmp/test.sql?192.168.84.138:/tmp?(復(fù)制到從服務(wù)器)
-如果主數(shù)據(jù)庫的服務(wù)可以停止,那么直接cp數(shù)據(jù)文件應(yīng)該是最快的生成快照的方法
-把數(shù)據(jù)庫的一致性備份恢復(fù)到從數(shù)據(jù)庫上,可以壓縮data文件夾后復(fù)制到從數(shù)據(jù)庫。
6) 主數(shù)據(jù)庫備份完畢后,主數(shù)據(jù)庫可以恢復(fù)寫操作,剩下的操作只需在從服務(wù)器上去執(zhí)行:
#?mysql>unlock?tables;
2.從服務(wù)器配置
1) 修改從數(shù)據(jù)庫的server-id,注意server-id的值必須唯一,也不能和主數(shù)據(jù)庫配置相同
#?vim?/etc/my.cnf ????server-id=2
命令窗口輸入:
mysql>change master to master_host=’192.168.84.130’
mysql>change master to master_user=’user1’
mysql>change master to master_password=’user1’
mysql>reset slave;
mysql>start slave;
mysql>show slave statusG
2) 執(zhí)行主服務(wù)器的test.sql文件
#?mysql?-uuser1?-puser1?test
3) 重啟mysql
#?service?mysqld?restart
3.數(shù)據(jù)庫無法同步情況 1)查看相應(yīng)的主從復(fù)制進(jìn)程方法有兩種: (1)processlist
mysql>show?processlistG 如出現(xiàn)state:waiting?for?master?to?send?event //連接主數(shù)據(jù)為成功,而且成功獲取bin-log state:has?read?all?ready?log;waiting?for?the?slave?i/o?thread?to?update?it //成功執(zhí)行bin-log日志,正在等待著去再次連接主數(shù)據(jù)庫并更新獲取bin-log日志;
(2)status;
mysql>show?slave?statusG 如出現(xiàn): Slave_IO_Running:Yes //此進(jìn)程負(fù)責(zé)從服務(wù)器從主服務(wù)器上讀取binlog日志,并寫入從服務(wù)器的中繼日志。 Slave_SQL_Running:Yes //此進(jìn)程負(fù)責(zé)讀取并且執(zhí)行中繼日志中的binlog日志, #注以上兩個都為Yes則表明成功,只要一個是no,則表示復(fù)制進(jìn)程停止,錯誤原因從“l(fā)ast_error”字段的值中看到。
2)從數(shù)據(jù)庫常用命令:
(1)start slave #啟動復(fù)制線程
(2)stop slave #停止復(fù)制線程
(3)show master status #查看從數(shù)據(jù)庫狀態(tài)
(4)show master logs #查看主數(shù)據(jù)庫bin-log日志
(5)change master to #動態(tài)改變主服務(wù)器的配置
(6)show processlist #查看從數(shù)據(jù)庫運行進(jìn)程
3)從數(shù)據(jù)庫無法同步
Show slave status 顯示Slave_SQL_Running為No,Second_Behind_Master為null
原因:
a.程序可能在slave上進(jìn)行了寫操作
b.也可能slave機器重啟后,事務(wù)回滾造成的
解決:方法一
Mysql>slave stop;
Mysql>set GLOBAL SQL_SLAVE_SKIPCOUNTER=1;
Mysql>slave start;
方法二
Slave庫,MySQL>slave stop –停掉slave服務(wù)
Master庫,MySQL>show master status;
得到主服務(wù)器上當(dāng)前的二進(jìn)制日志名和偏移量
查看狀態(tài),然后到slave服務(wù)器上執(zhí)行手動同步
mysql>change master to
master_host=”192.168.84.130”,
master_user=”user1”,
master_password=”user1”,
master_port=3306,
master_log_file=”mysql-bin.000001”,
master_log_pos=442;
啟動slave服務(wù),
Mysql>slave start;
通過show slave status 查看Slave_SQL_Running為Yes,Second_Behind_Master為0即為正常