mysql是常用的数据库,而为了保证数据的不丢失,mysql的主从成为很多企业的选择,里面牵涉到的原理简介如下:slave服务器通过Slave_IO_Running进程同步master数据库的bin-log日志,此日志记录了主mysql的sql操作,同步过来后slave服务器通过自己的Slave_sql――runing进程执行同步,这样做的好处是实现了读写分离。下面是具体搭建过程。
我用的是centos6.4,mysql为了简单用yum装好了。
1关闭防火墙,或者允许3306端口通过
2修改master服务器的my.cnf文件,我的主mysql的ip地址为192.168.112.122
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
server-id=2
log-bin=master-log
[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
修改后重启mysql,service mysqld restart
3登录主mysql
mysql -uroot -p123
grant replication slave on *.* to [email protected] identified by '123456';
flush privileges;
show master status;
+-------------------+----------+--------------+------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+-------------------+----------+--------------+------------------+
| master-log.000002 | 1408 | mysql | zabbix |
+-------------------+----------+--------------+------------------+
1 row in set (0.00 sec)
4对slave数据库进行配置
vi /etc/my.cnf
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
server-id=2
log-bin=master-log
[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
保存后重启mysql数据库
5登录从数据库
mysql -uroot -p12345678
stop slave;
change master to master_user='zhanghe', master_host='192.168.112.122', master_password='123456', master_port=3306, master_log_file='master-log.000002', master_log_pos=1408;
start slave;
show slave status\G;
如果 Slave_IO_Running: Yes Slave_SQL_Running: Yes则为配置成功
5.1如果Slave_IO_Running: No,我认为应该从三方面查看,1网络是否通,特别是虚拟机时必须是桥接模式2my.cnf配置有误3权限问题
5.2 如果Slave_SQL_Running:No
1.程序可能在slave上进行了写操作
2.也可能是slave机器重起后,事务回滚造成的.
解决办法:1.首先停掉Slave服务:slave stop
2.到主服务器上查看主机状态:
3.到slave服务器上执行手动同步:
mysql> change master to
> master_host='master_ip',
> master_user='user',
> master_password='pwd',
> master_port=3307,
> master_log_file='mysql-bin.000020',
> master_log_pos=135617781;
1 row in set (0.00 sec)
4 start slave;show slave status\G;
6在主数据库插入数据,看从数据库是否有数据