#mysql数据库 #主从
MySQL数据库主从配置
1.MySQL主从介绍
MySQL 主从又叫做 Replication、AB 复制。简单讲就是 A 和 B 两台机器做主
从后,在 A 上写数据,另外一台 B 也会跟着写数据,两者数据实时同步的。
MySQL 主从是基于 binlog 的,主上须开启 binlog 才能进行主从。
主从过程大致有 3 个步骤:
1)主将更改操作记录到 binlog 里
2)从将主的 binlog 事件(sql 语句)同步到从本机上并记录在 relaylog
里中继日志
3)从根据 relaylog 里面的 sql 语句按顺序执行
主配置(安装完 mysql 的虚拟机)
一台IP:192.168.13.5 我将这台虚拟机作为我的主服务器
一台IP:192.168.13.8 我将这台虚拟机作为我的从服务器
基础配置:
[root@localhost ~]# vi /etc/my.cnf进入MySQL的编辑文件

重启mysqld服务:(两种都可以)
错误:出现错误之后,可以查看MySQL的进程,如果有的话,请先全部kill掉
ps aux | grep mysql *kill -9 进程数据
[root@localhost ~]# /etc/init.d/mysqld restart
[root@localhost ~]# systemctl start mysqld.service
备份MySQL库(加入环境变量)
[root@localhost ~]# mysqldump -uroot mysql > /tmp/mysql.sql 输入该命令之后会存在命令不存在,可以通过添加mysql的环境变量


创建一个库保存数据(此库为同步库)
[root@localhost ~]# mysqldump -uroot -e "create database kei"
将MySQL库恢复成新建的库,作为测试数据,进行数据库配置
[root@localhost ~]# mysql -uroot进入数据库,创建同步数据的用户赋予权限
mysql> grant replication slave on *.* to 'repl' @192.168.13.5 identified by '204718';

提醒:此次进入的仅此为数据库,可以使用use MySQL或者是其他进入数据库,若是要进入MySQL数据库一定要进去,因为MySQL本身就含有一个MySQL数据库
将表锁住,保持表内的数据不变
mysql> flush tables with read lock;

显示主机的状态
mysql> show master status;

错误:这里一定要细心,要不然很有可能出现主机状态为空,配置MySQL文件的时候需要注释掉和需要留存的要分清楚,尤其是主配置中添加配置文件的时候。我们可以通过,ls -/data/mysql 查看有错误的地方(含有err即为错误日志)[root@localhost ~]# tail -15 /data/mysql/aminglinux.000001用这个命令查看错误日志。其中/data/mysql就是存放mysql数据库,后面就是二进制日志。


从配置(安装完mysql的虚拟机)
基础配置:
[root@localhost ~]# vi /etc/my.cnf进入MySQL的编辑文件

重启mysqld服务:(两种都可以)
[root@localhost ~]# /etc/init.d/mysqld restart
[root@localhost ~]# systemctl start mysqld.service
错误:出现错误之后,可以查看MySQL的进程,如果有的话,请先全部kill掉
ps aux | grep mysql *kill -9 进程数据
在主服务器上将文件拷贝到从上,并在从上查看两者的文件大小是否一致
[root@localhost ~]# scp /tmp/mysql.sql root@192.168.13.8:/tmp/这里填写的IP为从的
[root@localhost ~]# ls -la /tmp/mysql.sql

创建一个和主一样的库
[root@localhost ~]# mysqldump -uroot -e "create database kei"

将文件的内容导入库
[root@localhost ~]# mysql -uroot kei < /tmp/mysql.sql
[root@localhost ~]# mysql -uroot进入数据库,配置数据库
错误:此时的IP等一系列,要求的都是为主服务器的,log_file和log_pos都通过主配置的显示主机状态中得到。

在主上面执行解锁表
[mysql] > unlock tables;

进行验证的时候,需要刷新
主从同步以及相关配置参数
在从服务器上操作并执行命令,关闭防火墙
[mysql]>systemctl stop firewalld
[mysql]>setenforce 0
[mysql ]> show slave statusG


出现上面的这种即为正确的,表示配置正常。


配置参数
[root@localhost~]# vi /etc/my.cnf从

[root@localhost~]# vi /etc/my.cnf主

测试主从
主:进入同步的数据库(注意MySQL的本身含有MySQL数据库)
[root@localhost ~]# mysql -uroot
mysql> use kei由于我创建的用来同步的库为kei
mysql> select count(*)from db;

从:
[root@localhost ~]# mysql -uroot
mysql> use kei
mysql> select count(*)from db;
