技巧提示:mysql讀寫分離搭建好之後,配合nginx的負載均衡,可以高效的mysql的集群性能,同時免去麻煩的query分流。比如,sever1收到的請求就專門鏈接slave1從mysql讀取數據,配合nginx的反向代理實現的分流,就可以優雅的把mysql的query請求分壓到不同的mysql- ...
技巧提示:mysql讀寫分離搭建好之後,配合nginx的負載均衡,可以高效的mysql的集群性能,同時免去麻煩的query分流。比如,sever1收到的請求就專門鏈接slave1從mysql讀取數據,配合nginx的反向代理實現的分流,就可以優雅的把mysql的query請求分壓到不同的mysql-slave實例。如果不會搭建ngnix的同學可以看我上一篇文章《高併發教程-基礎篇-之nginx負載均衡的搭建》
一、架構圖:
伺服器準備: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上面查看是否有相關信息