MYSQL主从复制

mysql的主从架构有4种:
主从复制、并联复制、级联复制和双机热备

都有不同的优缺点,但它们有个共同的优点就是减少master的压力,master可以进行读写,slave可以进行读。我这里搭建的MySQL主从架构时主从复制

首先,准备好两台已经安装好mysql数据库的系统(注意:mysql的版本和操作系统的版本要一样)

实验环境:
操作系统:CentOS 7
mysql版本: mysql5.7

ip配置:

ip 主机名
192.168.2.131 Master
192.168.2.132 Slave

1、/etc/hosts文件的配置
在hosts文件加入(Master和Slave的hosts文件都加入)

192.168.2.131 Master
192.168.2.132 Slave

2、关闭防火墙和selinux(master和slave都执行)
[root@Master local]# systemctl stop firewalld
[root@Master local]# systemctl disable firewalld
MYSQL主从复制_第1张图片
临时关闭selinux,永久修改请修改配置文件/etc//etc/selinux/config,将SELINUX=enforcing
设置为SELINUX=disabled,然后重启使其生效

[root@Master local]# getenforce
Enforcing
[root@Master local]# setenforce 0
[root@Master local]# getenforce
Permissive

3、在master中创建从复制用户并授予replication slave权限

mysql> create user ‘repl’@‘192.168.2.132’ identified by ‘123456’;
Query OK, 0 rows affected (0.01 sec)

mysql> grant replication slave on . to ‘repl’@‘192.168.2.132’;
Query OK, 0 rows affected (0.33 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.32 sec)

4、锁定表,获取二进制日志文件名和位置,锁定是为防止二进制日志文件名和位置发生改变。
mysql> flush tables with read lock;
Query OK, 0 rows affected (0.00 sec)

mysql> show master status \G
*************************** 1. row ***************************
File: mysql-logbin.000002
Position: 1585
Binlog_Do_DB:
Binlog_Ignore_DB:
Executed_Gtid_Set:
1 row in set (0.00 sec)

5、配置主从两台系统同步(slave执行)
mysql> CHANGE MASTER TO MASTER_HOST=‘192.168.2.131’ ,MASTER_USER=‘repl’,MASTER_PASSWORD=‘123456’,MASTER_LOG_FILE=‘mysql-logbin.000002’,MASTER_LOG_POS=1585 ;

6、开启sql线程和IO线程
mysql> start slave;
查看slave的状态
mysql> show slave status \G
MYSQL主从复制_第2张图片
7、解表锁
mysql> unlock tables;
Query OK, 0 rows affected (0.00 sec)

8、测试主从复制是否安装成功

在master中创建一个数据库db_test,在数据库db_test创建一个表,表里插入一条数据。
mysql> create database db_test;
Query OK, 1 row affected (0.00 sec)

mysql> use db_test;
Database changed
mysql> create table test (a int,b int);
Query OK, 0 rows affected (0.14 sec)

mysql> insert into test values(1,2);
Query OK, 1 row affected (0.25 sec)

mysql> commit;
Query OK, 0 rows affected (0.00 sec)

在slave中进行查看
mysql> show databases;
±-------------------+
| Database |
±-------------------+
| information_schema |
| db_test |
| mysql |
| performance_schema |
| sys |
±-------------------+
5 rows in set (0.13 sec)

mysql> use db_test
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
±------------------+
| Tables_in_db_test |
±------------------+
| test |
±------------------+
1 row in set (0.00 sec)

mysql> select * from test;
±-----±-----+
| a | b |
±-----±-----+
| 1 | 2 |
±-----±-----+
1 row in set (0.00 sec)

你可能感兴趣的:(Mysql)