Mysql Replication 最简单配置

Google 一下Mysql Replication可以找到相关配置说明满地都是,作为双机热备方案很多时候需要用到,但是稍微看下这些资料发现都是乱七八糟的,所以果断去读MySQL 5.1 Reference Manual: 16.1.1. How to Set Up Replication。资料很长,不过最后总结的配置其实非常简单。

配置

1. In Master (例子IP 10.6.7.7)

my.cnf 添加这两行:

[mysqld]
log-bin=mysql-bin
server-id=1

终端中运行:

1
2
3
mysqldump -uroot -p --all-databases --master-data | gzip -9 -c > dbdump.db.gz
scp dbdump.db.gz user@10.6.7.8:~
echo "CREATE USER 'repl'@'%' IDENTIFIED BY 'slavepass'; GRANT REPLICATION SLAVE ON *.* TO 'repl'@'%';" | mysql -uroot -p

2. In Slave (例子IP 10.6.7.8)

my.cnf 添加和Master不同的ID:

[mysqld]
server-id=1001

终端中运行:

1
2
3
MASTER_IP=10.6.7.7
 
(echo "SLAVE STOP; CHANGE MASTER TO MASTER_HOST='$MASTER_IP', MASTER_USER='repl', MASTER_PASSWORD='slavepass';"; zcat dbdump.db.gz;echo "SLAVE START;") | mysql -uroot -p

OK, 收工。

验证

要验证同步,在Master执行:CREATE DATABASE test_repl;, 在Slave执行 SHOW DATABASES;,可以看到test_repl同步完成,在Master执行:DROP DATABASE test_repl;,Slave的也相应消失。

完整的启动LOG /var/log/mysql/error.log大致如下,可看到replication线程启动正常。

120424 16:34:51 [Note] Plugin 'FEDERATED' is disabled.
120424 16:34:52  InnoDB: Initializing buffer pool, size = 8.0M
120424 16:34:52  InnoDB: Completed initialization of buffer pool
120424 16:34:52  InnoDB: Started; log sequence number 0 1174665
120424 16:34:52 [Note] Slave SQL thread initialized, starting replication in log 'mysql-bin.000001' at position 1060, relay log './ub1110-relay-bin.000024' position: 251
120424 16:34:52 [Note] Event Scheduler: Loaded 0 events
120424 16:34:52 [Note] /usr/sbin/mysqld: ready for connections.
Version: '5.1.61-0ubuntu0.11.10.1'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  (Ubuntu)
120424 16:34:52 [Note] Slave I/O thread: connected to master 'repl@172.28.16.82:3306',replication started in log 'mysql-bin.000001' at position 1060

收尾

Slave的/var/log/mysql/error.log可能会看到一个warnning

120423 18:01:41 [Warning] Neither --relay-log nor --relay-log-index were used; so replication may break when this MySQL server acts as a slave and has his host name changed!! Please use '--relay-log=XXXXX-relay-bin' to avoid this problem.

如它所说,把这句加入到my.cnf[mysqld]即可。

日常维护

如果数据库操作频繁,binlog消耗的磁盘空间挺大的,设置Master的expire_logs_days可以控制存储binlog的文件个数。

如果留下了大堆binlog需要清理,可以执行这句清理7天前的binlog:

1
mysql -uroot -p -e "PURGE MASTER LOGS BEFORE DATE_SUB( NOW(), INTERVAL 7 DAY);"
文章分类 Mysql 标签: ,

发表评论

电子邮件地址不会被公开。 必填项已用*标注

*