mysql主从复制
合理的mysql主从复制需要3台机器,每台机器上都有mysql。 3台中,一台是master节点,负责数据写入。另外两台负责读取。 绝大多数的业务场景都是高读取、低写入。所以通过3个mysql配置成组合复制就能做出一个mysql的读写分离版本。
主从原理
- 当Master节点进行insert、update、delete操作时,会按顺序写入到binlog中。
- slave从库连接master主库,Master有多少个slave就会创建多少个binlog dump线程。
- 当Master节点的binlog发生变化时,binlog dump 线程会通知所有的salve节点,并将相应的binlog内容推送给slave节点。
- I/O线程接收到 binlog 内容后,将内容写入到本地的 relay-log。
- SQL线程读取I/O线程写入的relay-log,并且根据 relay-log 的内容对从数据库做对应的操作。
主从复制的详细理论介绍推荐这篇博客
配置主从复制
准备3台机器,每台机器都安装了mysql5.7。编译安装方法可以参考这篇博客: https://blog.csdn.net/qq_43626147/article/details/124732329
三台机器的ip: 10.0.0.101 master 10.0.0.102 slave1 10.0.0.103 slave2
master主节点配置
mysql -u root -p
Enter password: 123456
mysql> CREATE USER 'slave'@'%' IDENTIFIED BY '123456';
mysql> GRANT REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO 'slave'@'%';
mysql> flush privileges;
mysql> exit;
Bye
vim /etc/mysql/conf.d/mysql.cnf
-------------------------------
[mysqld]
server-id=1
log-bin=mysql-bin
binlog_ignore_db=mysql
systemctl restart mysqld
mysql -u root -p
Enter password: 123456
mysql> show master status;
+------------------+----------+--------------+------------------+-------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+------------------+----------+--------------+------------------+-------------------+
| mysql-bin.000001 | 769 | | | |
+------------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)
slave从节点配置
vim /etc/mysql/conf.d/mysql.cnf
-------------------------------
[mysqld]
relay-log=slave-bin
server-id=2
systemctl restart mysqld
mysql -u root -p
Enter password: 123456
mysql> change master to master_host='10.0.0.101',master_port=3306,master_user='slave',master_password='123456',master_log_file='mysql-bin.000001',master_log_pos=769;
mysql> start slave;
mysql> show processlist;
+----+-------------+-----------+------+---------+------+--------------------------------------------------------+------------------+
| Id | User | Host | db | Command | Time | State | Info |
+----+-------------+-----------+------+---------+------+--------------------------------------------------------+------------------+
| 2 | root | localhost | NULL | Query | 0 | starting | show processlist |
| 3 | system user | | NULL | Connect | 29 | Waiting for master to send event | NULL |
| 4 | system user | | NULL | Connect | 29 | Slave has read all relay log; waiting for more updates | NULL |
+----+-------------+-----------+------+---------+------+--------------------------------------------------------+------------------+
3 rows in set (0.00 sec)
mysql> show slave status;
到此主从复制就完成了。 实际上这个属于异步同步模式,是mysql默认的主从复制模式,如果你想实现半同步复制和GTID模式,自行百度,然后修改配置重启mysqld即可。
|