本文主要介绍在 MySQL 的主备同步设置方法。
备份配置文件,并添加要同步的数据库
- cd /etc/
- cp my.cnf my.cnf.bak
-
在my.cnf中添加如下内容
- # sync
- server-id=1 # 服务器 ID,要唯一
- log-bin=master-bin
- log_bin_index =master-bin.index
- binlog_do_db=mindoc_db # mindoc_db 是要同步的数据库的名称,后面验证数据同步时,就是同步该库的数据
- user=mysql
-
同样备份配置文件,
- cd /etc/
- cp my.cnf my.cnf.bak
-
在my.cnf中添加如下内容
- # sync
- server-id=2 # 服务ID
- log-bin=salve-bin
- relay-log =slave-relay-bin
- relay-log-index=slave-relay-bin.index
-
创建用于数据同步的用户
- # 登录 MySQL
- mysql -uroot -p
- mysql> create user 'sync'@'10.180.210.19' identified by 'Sync-123456'; # 创建用户 sync,设置密码 Sync-123456,并允许备库 10.180.210.19 登录
- mysql> flush privileges; # 刷新权限
- mysql> grant replication slave on *.* to 'sync'@'10.180.210.19' identified by 'Sync-123456' with grant option; # 赋予用户 sync 进行 replication slave 到备库 10.180.210.19 的权限
-
- # 查询 master 状态
- mysql> show master status;
- +-------------------+----------+--------------+------------------+-------------------+
- | File | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
- +-------------------+----------+--------------+------------------+-------------------+
- | master-bin.000001 | 121040 | mindoc_db | mysql | |
- +-------------------+----------+--------------+------------------+-------------------+
- 1 row in set (0.00 sec)
-
在备节点上设置主库信息
- mysql -uroot -p
-
- mysql> change master to master_host='10.180.249.18', master_port=3306, master_user='sync', master_password='Sync-123456', master_log_file='master-bin.000001', master_log_pos=121040;
-
- mysql> start slave;
- mysql> flush privileges;
-
- # 查询 slave 状态
- mysql> show slave status\G;
-
在主节点的数据库中添加数据,观察备节点是否能同步,如果能同步,则主备同步设置成功。