主从复制原理:
1、主从复制主要有一下三个步骤:(单向的)
- master将改变记录到二进制日志(binary log)中(这些记录叫做二进制日志事件,binary log events);
- slave将master的binary log events拷贝到它的中继日志(relay log);
- slave重做中继日志中的事件,将改变反映它自己的数据。
2、主从复制应用:
- 实时备份;
- 读写分离;
主从复制配置:
1、前期准备工作:
1)关闭防火墙、SELINUX:1
2
3
4[root@centOS1 ~]# service iptables stop
vi /etc/sysconfig/selinux
SELINUX=disabled
2)两台服务器:192.168.137.122 (master) 和 192.168.137.101 (slave) ,在上面安装一样的mysql版本。1
2
3
4
5[root@centOS1 ~]# rpm -qa | grep mysql
mysql-5.1.73-3.el6_5.x86_64
mysql-devel-5.1.73-3.el6_5.x86_64
mysql-libs-5.1.73-3.el6_5.x86_64
mysql-server-5.1.73-3.el6_5.x86_64
3)登录mysql删除空用户:
1 | mysql> SELECT user,host,password FROM mysql.user; |
2、主库上创建复制用户:1
2mysql> GRANT REPLICATION SLAVE,REPLICATION CLIENT ON *.* TO gechong@'%' IDENTIFIED BY 'gechong';
mysql> flush privileges;
3、修改配置文件:
1)主库需改配置文件,在/etc/my.cnf中添加1
2
3
4
5
6
7port = 3306
log_bin = /var/lib/mysql/mysql-binlog
server-id = 1 //只要主从不一样就行
binlog_do_db = test//要做同步的数据库名字,可以是多个数据库,之间用分号分割。
\# 忽略mysql系统库复制
binlog-ignore-db=mysql
binlog-ignore-db=information_schema
2)从库的配置文件中添加(/etc/my.cnf)1
2
3
4
5
6
7server-id = 2
master-host = 10.4.14.168
master-user = gechong
master-password = gechong
master-port = 3306
master-connect-retry = 5
replicate-do-db = test
然后分别重启mysql服务。
4、设置从库的同步位置:
1)查看主库状态:1
2
3
4
5
6mysql> show master status;
+---------------------+----------+--------------+--------------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+---------------------+----------+--------------+--------------------------+
| mysql-binlog.000002 | 265 | test | mysql,information_schema |
+---------------------+----------+--------------+--------------------------+
记住file和position两项。
2)从库设置同步日志位置:
1 | mysql> change master to |
3)从库上启动同步:
1 | mysql> slave start; |
4)从库上查看同步状态:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16mysql> show slave status\G
*************************** 1. row ***************************
Slave_IO_State: Waiting for master to send event
Master_Host: 192.168.137.122
Master_User: repli
Master_Port: 3306
Connect_Retry: 5
Master_Log_File: mysql-binlog.000002
Read_Master_Log_Pos: 265
Relay_Log_File: mysqld-relay-bin.000005
Relay_Log_Pos: 413
Relay_Master_Log_File: mysql-binlog.000002
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
Replicate_Do_DB: test
......
可以看到:Slave_IO_Running | Slave_SQL_Running两个值都是YES,说明配置成功了。
5、测试:
在主库上插入数据,在从库上查看插入信息。由于是单向的,所以只能在主库上执行DML操作;在从库上执行查询。