MySQL读写分离是指让master处理写操作,让slave处理读操作,非常适用于读操作量比较大的场景,可减轻master的压力。
使用mysql-proxy实现mysql的读写分离,mysql-proxy实际上是作为后端mysql主从服务器的代理,它直接接受客户端的请求,对SQL语句进行分析,判断出是读操作还是写操作,然后分发至对应的mysql服务器上。
实验主机(系统均为rhel6.5.x86_64):
master:172.25.40.2 server2
slave:172.25.40.1 server1
mysql-proxy:172.25.40.3 server3
首先我们需要配置一下主从复制,请查看之前的博客 mysql主从复制,配置完主从复制之后继续:
https://downloads.mysql.com/archives/get/file/mysql-proxy-0.8.5-linux-el6-x86-64bit.tar.gz #下载安装包
[root@server3 ~]# tar zxf mysql-proxy-0.8.5-linux-el6-x86-64bit.tar.gz
[root@server3 ~]# mv mysql-proxy-0.8.5-linux-el6-x86-64bit /usr/local/mysql-proxy
[root@server3 mysql-proxy]# cd bin
[root@server3 bin]# vim ~/.bash_profile
10 PATH=$PATH:$HOME/bin:/usr/local/mysql-proxy/bin
[root@server3 bin]# source ~/.bash_profile
[root@server3 mysql-proxy]# cd share/
[root@server3 share]# cd doc/
[root@server3 doc]# cd mysql-proxy/
[root@server3 mysql-proxy]# vim rw-splitting.lua
40 min_idle_connections = 1, 最小连接数
41 max_idle_connections = 2, 最大连接数
配置项可以通过以下命令查看
/usr/local/mysql-proxy/bin/mysql-proxy --help
[root@server3 mysql-proxy]# cd
[root@server3 ~]# cd /usr/local/mysql-proxy/
[root@server3 mysql-proxy]# mkdir conf
[root@server3 mysql-proxy]# mkdir logs
[root@server3 mysql-proxy]# cd conf/
[root@server3 conf]# vim mysql-proxy.conf
[mysql-proxy]
user=root
proxy-address=0.0.0.0:3306
proxy-read-only-backend-addresses=172.25.40.1:3306
proxy-backend-addresses=172.25.40.2:3306
proxy-lua-script=/usr/local/mysql-proxy/share/doc/mysql-proxy/rw-splitting.lua
log-file=/usr/local/mysql-proxy/logs/mysql-proxy.log
log-level=debug
daemon=true
keepalive=true
[root@server3 conf]# chmod 660 /usr/local/mysql-proxy/conf/mysql-proxy.conf
[root@server3 conf]# mysql-proxy --defaults-file=/usr/local/mysql-proxy/conf/mysql-proxy.conf
[root@server3 conf]# netstat -antlp
在mster给root一个远程登陆的权限
[root@server2 ~]# mysql -p
mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'Westos.123';
开启一个shell连接mysql
[root@foundation40 Desktop]# mysql -h 172.25.40.3 -u root -p
Enter password: #mysql登陆密码
MySQL [(none)]> use westos
MySQL [westos]> select * from userlist;
【server2】
[root@server2 ~]# yum install -y lsof
[root@server2 ~]# lsof -i :3306
[kiosk@foundation40 ~]$ mysql -h 172.25.40.3 -u root -p
Enter password:
MySQL [(none)]> use westos
MySQL [westos]> select * from userlist;
【server3】
【server2】
再次开启一个shell连接mysql
[kiosk@foundation40 ~]$ mysql -h 172.25.40.3 -u root -p
MySQL [(none)]> use westos
MySQL [westos]> select * from userlist;
[root@server1 ~]# yum install -y lsof
[root@server1 ~]# lsof -i :3306
MySQL [westos]> insert into userlist values ('user6','666');
通过tcpdump抓取数据分析读写分离
【server3】
[root@server3 ~]# yum install -y tcpdump
[root@server3 ~]# tcpdump -i eth0 port 3306