MySQL 运维 - 主从复制与读写分离
一、概述
单台MySQL服务器无法满足高可用和负载均衡,所以需要至少两台以上的MySQL服务器做主从复制以提高安全性和效率
二、应用场景
主服务器使用dump线程写入二进制日志文件,从服务器请求并通过I/O线程读取主服务器的日志并存入自己的中继服务器中,并通过SQL线程对主服务器更新的内容进行重读操作
三、案例实施
主机名 | 主机 | 操作系统 | IP 地址 | 主要软件 |
---|---|---|---|---|
CentOS 7-1 | Master | CentOS 7 | 192.168.0.10 | ntp 、 mysql-server |
CentOS 7-2 | Amoeba | CentOS 7 | 192.168.0.20 | jdk6、amoeba |
CentOS 7-3 | Slave1 | CentOS 7 | 192.168.0.30 | ntp 、ntpdate 、 mysql-server |
CengOS 7-4 | Slave2 | CentOS 7 | 192.168.0.40 | ntp 、ntpdate 、mysql-server |
CentOS 7-5 | 客户端 | CentOS 7 | 192.168.0.50 | mysql-client |
1. 建立时间同步环境
1.1 主服务器作为时间服务器
yum -y install ntp;
#进入ntp配置文件
vim /etc/ntp.conf
server 192.168.0.10
fudge 192.168.0.10 stratum 8
systemctl start ntpd
#查看同步状态
ntpq -p | ntpstat
1.2 在从服务器上进行时间同步
yum -y install ntp;
systemctl start ntpd
ntpdate 192.168.0.10
设置crontab定时同步
crontab -e
#每隔30分钟同步一次时间
*/30 * * * * ntpdate 192.168.0.10
2.配置主服务器MySQL
vim /etc/my.cnf
[mysqld]
server-id = 1
#开启二进制日志
log-bin=master-bin
#允许从服务器从主服务器更新日志
log-slave-updates=true
#重启服务
systemctl restart mysqld
mysql -uroot -p
#给从服务器授权
grant replication slave on *.* to 'myslave'@'192.168.0.%' identified by '123456';
#刷新权限
flush privileges;
#查看状态
show master status;
Position项记得保存下来
3.配置从服务器
vim /etc/my.cnf
[mysqld]
#ID要与Master不同,两个Slave的id也要不同
server-id = 2
#开启中继日志,从主服务器上同步日志文件记录到本地
relay-log=relay-log-bin
#定义中继日志文件的位置和名称
relay-log-index