欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

mysql主从配置实现一主一从读写分离

程序员文章站 2022-10-08 21:28:01
主从介绍Mysql主从又叫Replication、AB复制。简单讲就是A与B两台机器做主从后,在A上写数据,另外一台B也会跟着写数据,实现数据实时同步mysql主从是基于binlog,主上需开启binlog才能进行主从主从过程大概有3个步骤主将更改操作记录到binlog里从将主的binlog事件(s ......

主从介绍
mysql主从又叫replication、ab复制。简单讲就是a与b两台机器做主从后,在a上写数据,另外一台b也会跟着写数据,实现数据实时同步
mysql主从是基于binlog,主上需开启binlog才能进行主从
主从过程大概有3个步骤
主将更改操作记录到binlog里
从将主的binlog事件(sql语句) 同步本机上并记录在relaylog里
从根据relaylog里面的sql语句按顺序执行

mysql主从是异步复制过程
master开启bin-log功能,日志文件用于记录数据库的读写增删
需要开启3个线程,master io线程,slave开启 io线程 sql线程,
slave 通过io线程连接master,并且请求某个bin-log,position之后的内容。
master服务器收到slave io线程发来的日志请求信息,io线程去将bin-log内容,position返回给slave io线程。
slave服务器收到bin-log日志内容,将bin-log日志内容写入relay-log中继日志,创建一个master.info的文件,该文件记录了master ip 用户名 密码 master bin-log名称,bin-log position。
slave端开启sql线程,实时监控relay-log日志内容是否有更新,解析文件中的sql语句,在slave数据库中去执行。

主从作用
实时灾备,用于故障切换
读写分离,提供查询服务
备份,避免影响业务

主从形式
一主一从
一主多从(扩展系统读取的性能,因为读是在从库读取的)
多主一从(5.7之后开始)
主主复制
联机复制

主从复制步骤
主库将所有的写操作记录在binlog日志中,并生成log dump线程,将binlog日志传给从库的i/o线程
从库生成两个线程,一个是i/o线程,另一个是sql线程
i/o线程去请求主库的binlog日志,并将binlog日志中的文件写入relay log(中继日志)中
sql线程会读取relay loy中的内容,并解析成具体的操作,来实现主从的操作一致,达到最终数据一致的目的

主从复制配置步骤
确保从数据库与主数据库里的数据一致
在主数据库里创建一个同步账户授权给从数据库使用
配合主数据库(修改配置文件)
配置从数据库(修改配置文件)

需求
搭建两台mysql服务器,一台作为主服务器,一台作为从服务器,主服务器进行写操作,从服务器进行读操作

环境说明
数据库角色 ip 应用与系统 有无数据
主数据库 192.168.4.219 centos7 mysql-5.7 有
从数据库 192.168.4.218 centos7 mysql-5.7 无

在两台服务器上都按装mysql
环境准备
关闭防火墙以selinux
service iptables stop
sed -ri 's/(selinux=).*/\1disabled/g' /etc/selinux/config
setenforce 0

安装mysql
安装依赖包
yum -y install ncurses-devel openssl-devel openssl cmake mariadb-devel

创建用户和组
[root@yanyinglai ~]# groupadd -r -g 306 mysql
[root@yanyinglai ~]# useradd -m -s /sbin/nologin -g 306 -u 306 mysql

下载二进制格式的mysql软件包
--[root@yanyinglai ~]# cd /usr/src/
--[root@yanyinglai src]#wget https://downloads.mysql.com/archives/get/file/mysql-5.7.22-linux-glibc2.12-x86_64.tar.gz
已下载
[root@localhost ~]# cd soft/
[root@localhost soft]# ls -ltrh
total 1.2g
-rw-r--r--. 1 root root 566m jun 4 18:12 mysql-8.0.11-linux-glibc2.12-i686.tar.gz
-rw-r--r-- 1 root root 614m jun 13 16:54 mysql-5.7.22-linux-glibc2.12-x86_64.tar.gz

解压软件至/usr/local/
[root@localhost soft]# tar xf mysql-5.7.22-linux-glibc2.12-x86_64.tar.gz -c /usr/local/
[root@localhost soft]# ls /usr/local/
bin config config1 config2 etc games include jdk1.6 lib lib64 libexec mysql-5.7.22-linux-glibc2.12-x86_64 python3 sbin share src tomcat
[root@localhost soft]# cd /usr/local/

[root@localhost local]# ln -sv mysql-5.7.22-linux-glibc2.12-x86_64/ mysql
`mysql' -> `mysql-5.7.22-linux-glibc2.12-x86_64/'
[root@localhost local]# ll


修改目录/usr/locaal/mysql的属主属组
[root@localhost local]# chown -r mysql.mysql /usr/local/mysql
[root@localhost local]# ll /usr/local/mysql -d
lrwxrwxrwx 1 mysql mysql 36 jun 20 17:17 /usr/local/mysql -> mysql-5.7.22-linux-glibc2.12-x86_64/

添加环境变量

[root@localhost local]# ls /usr/local/mysql
bin copying docs include lib man readme share support-files
[root@localhost local]# cd
[root@localhost local]# echo 'export path=/usr/local/mysql/bin:$path' > /etc/profile.d/mysql.sh
[root@localhost local]# . /etc/profile.d/mysql.sh
[root@localhost local]# echo $path
/usr/local/mysql/bin:/usr/local/jdk1.6/bin:/usr/local/ssl/bin:/usr/local/mysql/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin

建立数据存放目录
[root@localhost local]# cd /usr/local/mysql
[root@localhost mysql]# mkdir -p /opt/data
[root@localhost mysql]# chown -r mysql.mysql /opt/data/
[root@localhost mysql]# ll /opt/
total 0
drwxrwxr-x 7 mysql mysql 4096 jun 18 15:25 data

初始化数据库
[root@yanyinglai mysql]# /usr/local/mysql/bin/mysqld --initialize --user=mysql --datadir=/opt/data/
//这个命令的最后会生成一个临时密码,后面修改初始密码需要

主库218
2019-06-20t09:21:02.883424z 1 [note] a temporary password is generated for root@localhost: qij(gork)2nt

备库219
2019-06-20t09:44:49.512519z 1 [note] a temporary password is generated for root@localhost: tu6w?erhvg7*

配置mysql
[root@localhost mysql]# ln -sv /usr/local/mysql/include/ /usr/local/include/mysql
`/usr/local/include/mysql' -> `/usr/local/mysql/include/'
[root@localhost mysql]# echo '/usr/local/mysql/lib' > /etc/ld.so.conf.d/mysql.conf
[root@yanyinglai ~]# ldconfig -v

生成配置文件,下面是显示结果
[root@localhost mysql]# cat > /etc/my.cnf <<eof
> [mysqld]
> basedir = /usr/local/mysql
> datadir = /opt/data
> socket = /tmp/mysql.sock
> port = 3306
> pid-file = /opt/data/mysql.pid
> user = mysql
> skip-name-resolve
> eof

执行下面的
cat > /etc/my.cnf <<eof
[mysqld]
basedir = /usr/local/mysql
datadir = /opt/data
socket = /tmp/mysql.sock
port = 3306
pid-file = /opt/data/mysql.pid
user = mysql
skip-name-resolve
eof

配置服务启动脚本
[root@localhost mysql]# cp -a /usr/local/mysql/support-files/mysql.server /etc/init.d/mysqld
[root@localhost mysql]# sed -ri 's#^(basedir=).*#\1/usr/local/mysql#g' /etc/init.d/mysqld
[root@localhost mysql]# sed -ri 's#^(datadir=).*#\1/opt/data#g' /etc/init.d/mysqld

启动mysql
[root@localhost mysql]# service mysqld start
starting mysql.logging to '/opt/data/localhost.localdomain.err'.
success!

[root@localhost mysql]# ps -ef|grep mysql
root 4897 1 0 22:38 pts/2 00:00:00 /bin/sh /usr/local/mysql/bin/mysqld_safe --datadir=/opt/data --pid-file=/opt/data/mysql.pid
mysql 5075 4897 6 22:38 pts/2 00:00:01 /usr/local/mysql/bin/mysqld --basedir=/usr/local/mysql --datadir=/opt/data --plugin-dir=/usr/local/mysql/lib/plugin --user=mysql --log-error=yanyinglai.err --pid-file=/opt/data/mysql.pid --socket=/tmp/mysql.sock --port=3306
root 5109 4668 0 22:38 pts/2 00:00:00 grep --color=auto mysql
[root@localhost mysql]# ss -antl
state recv-q send-q local address:port peer address:port
listen 0 128 *:22 *:*
listen 0 100 127.0.0.1:25 *:*
listen 0 128 :::22 :::*
listen 0 100 ::1:25 :::*
listen 0 80 :::3306

修改密码
使用临时密码修改
[root@yanyinglai ~]# mysql -uroot -p
mysql> set password = password('123456');
mysql> quit

mysql主从配置
确保从数据库与主数据库的数据一样先在主数据库创建所需要同步的库和表
[root@localhost mysql]# mysql -uroot -p123456
mysql> create database yan;
query ok, 1 row affected (0.00 sec)

mysql> create database lisi;
query ok, 1 row affected (0.00 sec)

mysql> create database wangwu;
query ok, 1 row affected (0.00 sec)

mysql> use yan;
database changed
mysql> create table tom (id int not null,name varchar(100)not null ,age tinyint);
query ok, 0 rows affected (11.83 sec)

mysql> insert tom (id,name,age) values(1,'zhangshan',20),(2,'wangwu',7),(3,'lisi',23);
query ok, 3 rows affected (0.07 sec)
records: 3 duplicates: 0 warnings: 0

mysql> select * from tom;

备份主库
备份主库时需要另开一个终端,给数据库上读锁,避免在备份期间有其他人在写入导致数据同步的不一致
[root@localhost mysql]# mysql -uroot -p123456

mysql> flush tables with read lock;
query ok, 0 rows affected (0.01 sec)

//此锁表的终端必须在备份完成以后才能退出(退出锁表失效)
备份主库并将备份文件传送到从库
[root@localhost ~]# mysqldump -uroot -p123456 --all-databases > /opt/all-20190620.sql
mysqldump: [warning] using a password on the command line interface can be insecure.
[root@localhost ~]# scp /opt/all-20190620.sql root@192.168.4.219:/opt/
解除主库的锁表状态,直接退出交互式界面即可

mysql> quit
bye

【同上步骤安装从库】

在从库上恢复主库的备份并查看是否与主库的数据保持一致
安装配置同上
[root@rdtest mysql]# mysql -uroot -p123456 < /opt/all-20190620.sql
mysql: [warning] using a password on the command line interface can be insecure.
[root@yanyinglai ~]# mysql -uroot -p123456
mysql> show databases;
mysql> use yan;
mysql> select * from tom;

主从配置

在主数据库创建一个同步账户授权给从数据使用 ip对应为slave的
[root@localhost ~]# mysql -uroot -p123456
mysql> create user 'repl'@'192.168.4.219' identified by '123456';
query ok, 0 rows affected (5.50 sec)

mysql> grant replication slave on *.* to 'repl'@'192.168.4.219';
query ok, 0 rows affected (0.04 sec)

mysql> flush privileges;
query ok, 0 rows affected (0.09 sec)

配置主数据库编辑配置文件
[root@localhost ~]# vi /etc/my.cnf
//添加以下内容
[mysqld]
basedir = /usr/local/mysql
datadir = /opt/data
socket = /tmp/mysql.sock
port = 3306
pid-file = /opt/data/mysql.pid
user = mysql
skip-name-resolve

//添加以下内容
//启用binlog日志
log-bin=mysql-bin
//主数据库服务器唯一标识符 主的必须必从大
server-id=1
log-error=/opt/data/mysql.log

重启mysql服务
[root@yanyinglai ~]# service mysqld restart
shutting down mysql..... success!
starting mysql.logging to '/opt/data/mysql.log'.
............................... success!
[root@yanyinglai ~]# ss -antl
state recv-q send-q local address:port peer address:port
listen 0 128 *:22 *:*
listen 0 100 127.0.0.1:25 *:*
listen 0 128 :::22 :::*
listen 0 100 ::1:25 :::*
listen 0 80 :::3306 :::*

[root@localhost ~]# mysql -uroot -p123456
查看主库的状态
mysql> show master status;
+------------------+----------+--------------+------------------+-------------------+
| file | position | binlog_do_db | binlog_ignore_db | executed_gtid_set |
+------------------+----------+--------------+------------------+-------------------+
| mysql-bin.000003 | 154 | | | |
+------------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)

配置从数据库
编辑配置文件

添加以下内容:
server-id=2 //设置从库的唯一标识符 从的必须比主小
relay-log=mysql-relay-bin //启用中继日志relay log
error-log=/opt/data/mysql.log

[root@rdtest mysql]# vi /etc/my.cnf
[mysqld]
basedir = /usr/local/mysql
datadir = /opt/data
socket = /tmp/mysql.sock
port = 3306
pid-file = /opt/data/mysql.pid
user = mysql
skip-name-resolve

server-id=2
relay-log=mysql-relay-bin
log-error=/opt/data/mysql.log

重启从库的mysql服务
[root@rdtest mysql]# service mysqld restart
shutting down mysql.. success!
starting mysql.logging to '/opt/data/mysql.log'.
success!
[root@rdtest mysql]# ss -antl
state recv-q send-q local address:port peer address:port
listen 0 128 :::22 :::*
listen 0 128 *:22 *:*
listen 0 100 ::1:25 :::*
listen 0 100 127.0.0.1:25 *:*
listen 0 10 *:5672 *:*
listen 0 80 :::3306 :::*
[root@rdtest mysql]#

配置并启动主从复制
主节点的二进制文件一定要是二进制列表中的最后一个二进制文件
mysql> change master to
-> master_host='192.168.4.218', //主库ip
-> master_user='repl',//复制用户
-> master_password='123456',//用户密码
-> master_log_file='mysql-bin.000003',
-> master_log_pos=154;
query ok, 0 rows affected, 2 warnings (0.00 sec)

change master to
master_host='192.168.4.218',
master_user='repl',
master_password='123456',
master_log_file='mysql-bin.000003',
master_log_pos=154;

查看从服务器状态

mysql> show slave status\g;
slave_io_running: yes //此处必须是yes
slave_sql_running: yes //此处必须是yes

error:
no query specified
测试验证在主服务器的yan库的tom表插入数据:
mysql> use yan;
mysql> select * from tom;
mysql> insert tom(id,name,age) value (4,"zgy",18);
query ok, 1 row affected (0.14 sec)
mysql> select * from tom;

insert tom(id,name,age) value (5,"zgy",16);
update tom set name='yyyyy' where age=18;
delete from tom where age=18;

在从数据库查看是否数据同步
mysql> use yan;
mysql> select * from tom;

关注slave_io_state,slave_io_running,slave_sql_running状态
若都为yes状态时确认同步配置完成

【检查】
查看主库二进制日志是否开启
mysql> show global variables like '%log%';
| log_bin | on |

查看主节点二进制日志列表
mysql> show master logs;
查看主节点的server id
mysql> show global variables like '%server%';
| server_id | 1 |

mysql> show global variables like '%log%';
| log_bin | off |

| relay_log | mysql-relay-bin |
| relay_log_basename | /opt/data/mysql-relay-bin |
| relay_log_index | /opt/data/mysql-relay-bin.index |

mysql> show global variables like '%server%';

| server_id | 2 |

从库
开启中继日志
添加:relay-log=relay-log
添加:relay-log-index=relay-log.index
添加:server-id=2
添加:innodb_file_per_table=on
添加:skip_name_resolve=on

查看进程
mysql> show processlist;

查看表结构
mysql> show create table tom \g
*************************** 1. row ***************************
table: tom
create table: create table `tom` (
`id` int(11) not null,
`name` varchar(100) not null,
`age` tinyint(4) default null
) engine=innodb default charset=latin1
1 row in set (0.00 sec)

执行计划
mysql> explain select * from tom;
+----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+-------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | extra |
+----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+-------+
| 1 | simple | tom | null | all | null | null | null | null | 5 | 100.00 | null |
+----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+-------+
1 row in set, 1 warning (0.00 sec)

限制从服务器为只读
从服务器 read_only = on,但是此限制对拥有super权限的用户均无效。
阻止所有用户
mysq>flush tables with read lock;

【从库只读】
需要保证master-slave主从同步的salve库,如果要设置为只读状态,可以限定普通用户进行数据修改的操作,但不会限定具有super权限的用户
set global read_only=1;

查询有哪些数据库
show databases;
查询某数据库有哪些表
use mysql
show tables;
获取binlog文件列表
show binary logs;
只查看第一个binlog文件的内容
show binlog events;
查看指定binlog文件的内容
show binlog events in 'mysql-bin.000001';

初始化异常处理
[root@rdtest mysql]# ./bin/mysqld --initialize --user=mysql --datadir=/opt/data/
./bin/mysqld: error while loading shared libraries: libaio.so.1: cannot open shared object file: no such file or directory
安装一下
[root@rdtest mysql]# yum install -y libaio
[root@rdtest mysql]# ./bin/mysqld --initialize --user=mysql --datadir=/opt/data/
2019-06-13t09:28:47.897255z 1 [note] a temporary password is generated for root@localhost: 4tb,9q+&j3he

error: protected multilib versions: libstdc++-4.4.7-23.el6.i686 != libstdc++-4.4.7-17.el6.x86_64
you could try using --skip-broken to work around the problem
you could try running: rpm -va --nofiles --nodigest
安装下面的包
yum --skip-broken update
yum clean all
yum install libstdc++.so.6