背景
- 两台linux服务器(A和B)
- 别人随手安装的mysql5.7
前言
由于内网环境,本次不考虑负载均衡,只同步数据库起到备份的作用;如果要负载均衡需要代码读写分离(估计没人这么做)或使用中间件(Mycat等)再或者使用其他集群
安装步骤
主服务器
- 修改配置文件
vim my.cnf
## 输入如下内容
[mysqld]
log-bin=mysql-bin #开启二进制日志
server-id=1 #服务id,不可重复,最好是服务器ip最后一位
- 创建同步账户以及授权
mysql -u root -p
CREATE USER 'repl'@'%' IDENTIFIED BY 'repl'; #创建账号
GRANT REPLICATION SLAVE ON *.* TO 'repl'@'%'; #授权
flush privileges; #刷新
- 重启mysql
一般使用servcie mysqld restart
即可,如果不行直接进入mysql路径/support-files/
目录下
./mysqld restart
即可
- 查看状态
进入mysql show master status
, file和position两列是后面需要使用的参数
扩充:
# 查看二进制日志相关的配置项:
show global variables like 'binlog%';
# 查看server相关的配置项
show global variables like 'server%';
从服务器
- 修改配置文件
vim my.cnf
## 输入如下内容
[mysqld]
server-id=2
- 重启mysql
- 进入mysql并设置master相关信息
change master to
master_host='主服务器id',
master_user='repl',
master_password='repl',
master_port=3306,
master_log_file='刚刚查到的file一列',
master_log_pos=查到的position一列,没引号;
- 启动同步
start slave;
- 查看master状态
show slave status;
如果Slave_IO_Running和Slave_SQL_Running两列均为yes,即成功
测试
在master中创建表、插入数据均会自动同步到从服务器中
参考文档
https://segmentfault.com/a/1190000017049567
https://www.bilibili.com/video/BV1R4411s7zi?p=10
https://www.jianshu.com/p/276d59cbc529(mysql安装步骤)
补充
[mysqld]
lower_case_table_names=1 #设置表名不区分大小写
max_connections=3600 #设置最大连接数
character_set_server=utf8 #设置数据库默认字符集
show variables like '%max_connection%'; #查看最大连接数
set global max_connections=3600; #重新设置最大连接数
后续遇到的问题
- my.cnf修改最大连接数max_connections没有生效
1)在/etc/security/limits.conf末尾添加以下两行
mysql hard nofile 65535
mysql soft nofile 65535
- too many connections,但是没有连接;使用
df -h
显示磁盘占用100%,通过du -sh /xxx
和find / -type f -size +500M
找到大于500M的文件,发现是mydata里的主从日志文件。
1) 进入mysql中,使用reset master;
即可删除mysql-bin主从日志文件
2) 在my.cnf文件中设置expire_logs_days = 7
设定日志文件保留的天数
Q.E.D.