MySQL 的 Master-Slave Replication (同步) 是当 Master 数据库有变动时, 自动同步到 Slave 数据库。由于 MariaDB 在 RHEL/CentOS 7 开始已经成为默认数据库, 而且可以完全取代 MySQL, 所以以下也会以 MariaDB 进行设定, 但同样方法在 MySQL 一样可以的。
假设已经有两台 MySQL 服务器, 以下两部份分别是 Master 及 Slave 的设定。
Master
开启 /etc/my.cnf 进行设定, 在 [mysqld] 区块改成以下这样, 其中 bind-address 要改成 Master 的 ip; datadir 是资料目录:
|
1 2 3 4 5 6 7 8 9 |
[mysqld] bind-address=192.168.1.100 server-id=1 binlog-ignore-db = "mysql" binlog-format = mixed log-bin=mysql-bin datadir=/var/lib/mysql innodb_flush_log_at_trx_commit=1 sync_binlog=1 |
修改后储存盘案, 重新启动 MySQL:
接着用 root 登入 MySQL, 建立一个用作同步的帐号, 以下会建立帐号 replication, 密码是 password, Slave 的 ip 是 192.168.1.101:
|
1 2 3 4 5 |
MariaDB> CREATE USER replication@192.168.1.101; MariaDB> GRANT REPLICATION SLAVE ON *.* TO replication@192.168.1.101 IDENTIFIED BY 'password'; MariaDB> flush privileges; MariaDB> SHOW MASTER STATUS; MariaDB> exit; |
然后要用 mysqldump 汇出数据库的 .sql 档, 要放到 Slave 汇入:
Slave 设定
开启 /etc/my.cnf 修改设定, 加入以下内容到 [mysqld] 区块:
|
1 2 3 4 5 6 7 |
[mysqld] server-id=2 binlog-format=mixed log_bin=mysql-bin relay-log=mysql-relay-bin log-slave-updates=1 read-only=1 |
修改后储存盘案, 重新启动 MySQL:
用 root 登入 MySQL, 建立数据库:
|
1 2 |
MariaDB> create database database-name; MariaDB> exit; |
将在 Master 用 mysqldump 建立的 masterdatabase.sql 汇入:
汇入资料后, 再次用 root 登入 MySQL, 执行以下 SQL 指令, 以下的 MASTER_HOST 改为 Master 的 ip, 而 MASTER_LOG_FILE 及 MASTER_LOG_POS 是在 Master 上在 MySQL 执行 “SHOW MASTER STATUS;” 的结果:
|
1 2 3 |
MariaDB> CHANGE MASTER TO MASTER_HOST='192.168.1.100',MASTER_USER='replication',MASTER_PASSWORD='password', MASTER_LOG_FILE='mariadb-bin.000001', MASTER_LOG_POS=500; MariaDB> START SLAVE; MariaDB> SHOW SLAVE STATUS \G; |
现在 Slave 已经可以同步, 要查询 Slave 的状态, 可以登入 MySQL 用以下指令检查:
|
1 2 |
MariaDB> START SLAVE; MariaDB> SHOW SLAVE STATUS \G; |