MySQL主从复制

一、主从复制的原理

  1. master服务器将数据的改变记录二进制日志,当master上的数据发生改变时,则将其改变写入二进制日志中;
  2. salve服务器会在一定时间间隔内对master二进制日志进行探测其是否发生改变,如果发生改变,则开始一个I/OThread请求master二进制事件;
  3. 同时主节点为每个I/O线程启动一个dump线程,用于向其发送二进制事件,并保存至从节点本地的中继日志中;
  4. 从节点将启动SQL线程从中继日志中读取二进制日志,在本地重放,使得其数据和主节点的保持一致;
  5. 最后I/OThread和SQLThread将进入睡眠状态,等待下一次被唤醒。

二、搭建主从复制(一主一从)

涉及主机:

主机名IP地址
db01(master)192.168.112.40
db02(slave)192.168.112.50

1、两台主机安装MySQL

#二进制安装
wget https://downloads.mysql.com/archives/get/p/23/file/mysql-5.6.40-linux-glibc2.12-x86_64.tar.gz
tar xzvf mysql-5.6.40-linux-glibc2.12-x86_64.tar.gz
mkdir /application
mv mysql-5.6.40-linux-glibc2.12-x86_64 /application/mysql-5.6.40
ln -s /application/mysql-5.6.40/ /application/mysql
cd /application/mysql/support-files/
\cp my-default.cnf /etc/my.cnf
cp mysql.server /etc/init.d/mysqld
cd /application/mysql/scripts
useradd mysql -s /sbin/nologin -M
yum -y install autoconf
cd /application/mysql/scripts/
./mysql_install_db --user=mysql --basedir=/application/mysql --data=/application/mysql/data
echo 'export PATH="/application/mysql/bin:$PATH"' >> /etc/profile.d/mysql.sh
source /etc/profile
sed -i 's#/usr/local#/application#g' /etc/init.d/mysqld /application/mysql/bin/mysqld_safe
#指定MySQL安装根目录以及数据目录
vim /etc/my.cnf
basedir = /application/mysql/
datadir = /application/mysql/data
#设置密码
mysqladmin -uroot password '123'

2、修改配置文件

vim /etc/my.cnf
#主库
server_id=1
log_bin=mysql-bin
binlog_format=row
#从库
server_id=2

3、创建主从复制用户

#登录数据库
[root@db01 ~]# mysql -uroot -p123
#创建slave用户
mysql> grant replication slave on *.* to slave@'192.168.112.%' identified by '123';
Query OK, 0 rows affected (0.00 sec)

4、主从库重启并验证server_id

主从库重启

/etc/init.d/mysqld restart
#遇到重启失败
[root@db02 ~]# /etc/init.d/mysqld restart
 ERROR! MySQL server PID file could not be found!
Starting MySQL.Logging to '/application/mysql/data/db02.err'.
...........^C
[root@db02 ~]#
[root@db02 ~]# mysqladmin -uroot -p123 shutdown
Warning: Using a password on the command line interface can be insecure.
[root@db02 ~]# /etc/init.d/mysqld restart
Shutting down MySQL.. SUCCESS!
Starting MySQL. SUCCESS!

验证server_id

mysql> show variables like "server_id";

验证主库的binlog是否开启

mysql> show variables like "%bin%";

5、配置从库与主库的复制关系

#从库
change master to
master_host='192.168.112.40',
master_user='slave',
master_password='123',
master_log_file='mysql-bin.000001',
master_log_pos=120;
start slave;
show slave status\G;

主库使用show master status;

查看master_log_file和master_log_pos

6、验证主从复制

目前两个数据库数据是一致的

主库创建t1表并插入数据

可以看到从库也同步复制了主库更新的数据

至此主从复制配置完成

作者:misakivv原文地址:https://www.cnblogs.com/misakivv/p/18102266

%s 个评论

要回复文章请先登录注册