mysql的热备/Replication
mysql的双机热备机制其实比较简单。
几点注意的:
- 采用的是Master-Slave机制。Slave会从Master读取数据。
- Master必须打开二进制日志功能,通过my.cnf中的log-bin参数。
- 需要Master上建立一个备份用户。
- 通过Server-id来区别主/备。
- 第一次必须将数据完整同步,记得将Master锁定,导出,然后导入到备,设置好所有的Replication之后,unlock Master的表。
下面是Master的my.cnf参数:
server-id = 1
log-bin
binlog-do-db = ucenter
binlog-ignore-db = bbs
Server-id代表服务器编号。1是Master。Slave通过这个来同步。
需要启用二进制日志。log-bin可以指定log文件名称,也可以不写默认主机名。
下面是要备份和不要备份的database名称。
查看状态:
mysql> show master status\G;
如下:
mysql> show master status\G;
*************************** 1. row ***************************
File: mysql-bin.000110
Position: 2602
Binlog_Do_DB: ucenter
Binlog_Ignore_DB: bx8,card,cmsware_plus2,cmsware_zone,comsenzcensor,d6,d61,d61new,d62,d63,discuz,discuzzone,disuczbackup,dz2,dzzone,mysql,nauzone,nauzone1,nauzone2,tzsc,uc,uch,uchome,wikidb,wp,xmjc
1 row in set (0.00 sec)ERROR:
No query specified
记录下二进制日志以及Position。这里分别是mysql-bin.000110和2602,后面要用到。
下面是Slave的参数
启动mysql,然后进入mysql命令行
mysql> change master to
-> master_host = 'ip_address',
-> master_user = 'username',
-> master_password = 'password',
-> master_log_file = 'mysql-bin.000110',
-> master_log_pos = 2602;
注意最后两个参数,是前面记下来的参数。
这时候在Master上会有这个进程:
*************************** 3. row ***************************
Id: 939737
User: replication
Host: 210.28.92.215:56520
db: NULL
Command: Binlog Dump
Time: 556
State: Has sent all binlog to slave; waiting for binlog to be updated
Info: NULL
当然,Slave上也会有对应的进程:
*************************** 2. row ***************************
Id: 5
User: system user
Host:
db: NULL
Command: Connect
Time: 609
State: Waiting for master to send event
Info: NULL
*************************** 3. row ***************************
Id: 6
User: system user
Host:
db: NULL
Command: Connect
Time: -27246
State: Has read all relay log; waiting for the slave I/O thread to update it
Info: NULL
3 rows in set (0.00 sec)
Troubleshoot
第一次做的时候show processlist,老是卡在Queueing master event to the relay log状态,当然也没法同步了。
[root@mysql-replication mysql]# tail /usr/local/mysql/var/mysql-replication.err
错误提示如下:
090802 10:01:07 [ERROR] Error reading packet from server: File './mysql-bin.000005' not found (Errcode: 2) ( server_errno=29)
090802 10:01:07 [Note] Slave I/O thread: Failed reading log event, reconnecting to retry, log 'mysql-bin.000004' at postion 98
好像是读取binlog错误。
然后看/usr/local/mysql/var下面无数的二进制文件..
参考这个:
http://bbs.chinaunix.net/viewthread.php?tid=1311931&extra=&page=2
是由于数据不同步造成的。
解决办法:
首先,Master上
mysql> flush tables with read lock;
将表锁定。然后将需要备份的数据库打包移动到Slave数据库上。
Master上
启动Slave的MySQL,运行以下命令