这篇介绍基于日志的主从同步,适用于低版本的数据库同步。
一、主库
my.cnf,在[mysqld]下面加入:
server-id = 1
log-bin =mysql-bin
binlog_format = mixed
log=/data/mysql/data/mysql.log
max_connections = 100
max_connect_errors = 10
expire_logs_days = 99
开通用于binlog 复制的用户
CREATE USER 'repl'@ '%' IDENTIFIED BY 'repl_password';
GRANT REPLICATION SLAVE ON . TO 'repl'@'%' IDENTIFIED BY 'repl_password';
锁表防写入
FLUSH TABLES WITH READ LOCK;
获得基础备份
mysqldump -uroot -ppassword --all-databases --lock-tables=false > /root/all.sql
mysqldump -uroot -ppassword --single-transaction --master-data=2 --all-databases | gzip >all.sql.gz //备份数据库
使用scp命令传输数据库文件all.sql到从服务器
scp /root/all.sql root@x.x.x.x:/root
gzip -cd all.sql.gz | /usr/local/mysql/bin/mysql -u root -ppassword
//还原数据库
再次连接数据库进入mysql命令行查看master状态
mysql>SHOW MASTER STATUS;
得到binlog 文件和binlog pos
mysql-bin.000009 107
解锁数据表
mysql>UNLOCK TABLES;
二、从库
my.cnf,在[mysqld]下面加入:
log-bin=mysql-bin #不是必须
binlog_format=mixed #跟随log-bin,不是必须
server-id=2
log_slave_updates
skip_slave_start
log=/data/mysql/data/mysql.log
max_connections = 100
max_connect_errors = 10
expire_logs_days = 99
character_set_server = utf8
service mysqld restart
导入主服务器的数据库
mysql -u root -ppassword < /root/all.sql
登录mysql服务器,执行以下命令
CHANGE MASTER TO MASTER_HOST='x.x.x.x',MASTER_USER='repl',MASTER_PASSWORD='repl_password',MASTER_PORT=3306,MASTER_LOG_FILE='mysql-bin.000009',MASTER_LOG_POS =107;
开启从库复制
start slave
show slave status G
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
\如果此2项都为yes,master-slave配置即成功