主从架构的特点:
1、成本低,布署快速、方便
2、读写分离
3、还能通过及时增加从库来减少读库压力
4、主库单点故障
5、数据一致性问题(同步延迟造成)
主从复制:
MySQL内建的复制功能是构建大型,高性能应用程序的基础通过将MySQL的某一台主机(master)的数据复制到其他主机(slaves)上,并重新执行一遍来执行复制过程中一台服务器充当主服务器,而其他一个或多个其他服务器充当从服务器。
为什么要做主从复制?为了灾备、数据分布、负载平衡读写分离、提高并发能力。
准备
master:192.168.80.129
修改配置文件
[root@localhost ~]# vim /etc/my.cnf.d/mysql-server.cnf
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
log-error=/var/log/mysql/mysqld.log
pid-file=/run/mysqld/mysqld.pid
gtid-mode=on
enforce-gtid-consistency=true
log_bin=mysql-bin
server_id=120
重启数据库
[root@localhost ~]# systemctl restart mysqld.service
建立同步账号
#创建用户
mysql> create user 'rep'@'192.168.80.%' identified with mysql_native_password by'root';
Query OK, 0 rows affected (0.02 sec)
#授权
mysql> grant replication slave on *.* to 'rep'@'192.168.80.%';
Query OK, 0 rows affected (0.00 sec)
#刷新权限
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)
# 查看授权
mysql> show grants for 'rep'@'192.168.80.%';
+--------------------------------------------------------+
| Grants for rep@192.168.80.% |
+--------------------------------------------------------+
| GRANT REPLICATION SLAVE ON *.* TO `rep`@`192.168.80.%` |
+--------------------------------------------------------+
1 row in set (0.00 sec)
# 锁表的方式设置只读,为后面备份准备,注意生产环境要提前申请停机时间
mysql> flush tables with read lock;
Query OK, 0 rows affected (0.00 sec)
# 测试锁表后是否可以创建数据库:
mysql> flush tables with read lock;
Query OK, 0 rows affected (0.00 sec)
# 查看数据库的用户
mysql> select host,user from mysql.user;
+--------------+------------------+
| host | user |
+--------------+------------------+
| % | root |
| 192.168.80.% | rep |
| localhost | mysql.infoschema |
| localhost | mysql.session |
| localhost | mysql.sys |
+--------------+------------------+
5 rows in set (0.00 sec)
备份数据库数据
[root@localhost ~]# mysqldump -uroot -p'root' -A -B |gzip > /server/backup/mysql_bak.$(date +%F).sql.gz
解锁
mysql> unlock tables;
主库备份数据并上传到从库
[root@localhost ~]# scp backup/mysql_bak.2022-09-11.sql.gz localhost:/backup/
slaves:192.168.80.133
从库配置
[root@localhost ~]# vim /etc/my.cnf.d/mysql-server.cnf
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
log-error=/var/log/mysql/mysqld.log
pid-file=/run/mysqld/mysqld.pid
gtid-mode=on
enforce-gtid-consistency=true
log_bin=mysql-bin
server_id=130
重启数据库
还原从主库备份数据
# cd /server/backup/
# gzip -d mysql_bak.2015-11-18.sql.gz
# mysql -uroot -p < mysql_bak.2015-11-18.sql
检查还原:
# mysql -uroot -p -e 'show databases;'
设定从主库同步
mysql> change master to MASTER_HOST='192.168.95.120', MASTER_PORT=3306, MASTER_USER='rep', MASTER_PASSWORD='123456', MASTER_LOG_FILE='mysql-bin.000003', MASTER_LOG_POS=329;
启动从库同步开关
mysql> start slave;
检查状态:
mysql> show slave status\G
Slave_IO_Running: IO 线 程 是 否 打 开 YES/No/NULL Slave_SQL_Running: SQL线程是否打开 YES/No/NULL Seconds_Behind_Master: NULL #和主库比同步的延迟的秒数
测试主从同步:
主库创建一个数据库:
# mysql -uroot -p -e 'create database test_m_s;
从库检查:
# mysql -uroot -p -e 'show databases;' |grep "test_m_s"