技巧提示:mysql读写分离搭建好之后,配合nginx的负载均衡,可以高效的mysql的集群性能,同时免去麻烦的query分流。比如,sever1收到的请求就专门链接slave1从mysql读取数据,配合nginx的反向代理实现的分流,就可以优雅的把mysql的query请求分压到不同的mysql-slave实例。
一、架构图:
服务器准备:3台,ubuntu16.04系统+mysql-5.7.22-0ubuntu0.16.04.1
master:192.168.1.190 master-mysql
slave1:192.168.1.191 slave1-mysql
slave2:192.168.1.192 slave2-mysql
slave3:192.168.1.193 slave3-mysql
[注意:nginx集群搭建这里不做说明]
二、MYSQL安装和主从配置(分别在四台服务器上面进行如下操作)
1.ubuntu 16.04下安装mysql
sudo apt-get install mysql-server mysql-client
2.配置主服务器(master-mysql):
vim /etc/mysql/mysql.conf.d/mysqld.cnf 在[mysqld]分段下面添加 server-id=190 log_bin=/var/log/mysql/mysql-bin.log binlog_do_db=demos_db binlog_ignore_db=mysql 重启mysql: service mysql restart 查看是否已经开启二进制日志功能 show variables like 'log%'; 如果看到 log_bin ON 说明成功 +----------------------------------------+--------------------------------+ | Variable_name | Value | +----------------------------------------+--------------------------------+ | log_bin | ON | 查看二进制日志的位置: show master status; 可以看到 +------------------+----------+--------------+------------------+-------------------+ | File | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set | +------------------+----------+--------------+------------------+-------------------+ | mysql-bin.000007 | 923 | | | | +------------------+----------+--------------+------------------+-------------------+ 授权repl用户可以对主服务器二进制日志的读取: create user repl; grant replication slave,reload,super on *.* to 'repl'@'192.168.1.%' identified by '123456'; flush privileges; 3.从服务器的配置(以191为例,其他服务器把server-id=191改为对应的IP地址即可): vim /etc/mysql/mysql.conf.d/mysqld.cnf 在[mysqld]分段下面添加 server-id=191 log_bin=/var/log/mysql/mysql-bin.log replicate_do_db=demos_db 登录mysql,然后执行: stop slave; 确保slave都关闭。 然后设置从master复制日志配置: change master to master_host='192.168.1.190', master_user='repl', master_password='123456', master_log_file='mysql-bin.000007', master_log_pos=923; 注意1,master_log_file为在master运行show master status;看到的File字段下的文件名称;master_log_pos为Postition下看到的数值. 接着执行: start slave; show slave status/G; 可以看到如下信息 *************************** 1. row *************************** Slave_IO_State: Waiting for master to send event Master_Host: 192.168.1.190 Master_User: repl Master_Port: 3306 Connect_Retry: 60 Master_Log_File: mysql-bin.000007 Read_Master_Log_Pos: 923 Relay_Log_File: slave1-relay-bin.000002 Relay_Log_Pos: 320 Relay_Master_Log_File: mysql-bin.000007 Slave_IO_Running: Yes Slave_SQL_Running: Yes Replicate_Do_DB: demos_db ...... 注意:在出现的信息中找到 Slave_IO_Running/Slave_SQL_Running ,都为YES则成功了
三、操作测试:
在master上面: CREATE DATABASE demos_db DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci; CREATE TABLE tb1 (id int(11),name varchar(20)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; insert into tb1 values (1, "我是测试1"); 然后在其他salves上面查看是否有相关信息
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/6809.html