MySQL读写分离是指让master处理写操作,让slave处理读操作,非常适用于读操作量比较大的场景,可减轻master的压力。
使用mysql-proxy实现mysql的读写分离,mysql-proxy实际上是作为后端mysql主从服务器的代理,它直接接受客户端的请求,对SQL语句进行分析,判断出是读操作还是写操作,然后分发至对应的mysql服务器上。
实验主机(系统均为rhel6.5.x86_64):
172.25.254.1 server1 master
172.25.254.2 server2 slave
172.25.254.3 server3 mysql-proxy
首先我们需要配置一下主从复制,请查看之前的博客 mysql主从复制,配置完主从复制之后继续:
1、安装
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, 最大连接数
2、mysql-proxy配置启动文件
配置项可以通过以下命令查看
/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
3、启动mysql-proxy
[root@server3 conf]# mysql-proxy --defaults-file=/usr/local/mysql-proxy/conf/mysql-proxy.conf
4、查看监听端口
[root@server3 conf]# netstat -antlp
5、测试:
在mster给root一个远程登陆的权限
mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'Jane.123';
Query OK, 0 rows affected, 1 warning (0.05 sec)
开启一个shell连接mysql
[kiosk@foundation66 Desktop]$ mysql -h 172.25.254.3 -u root -p
Enter password: #mysql登陆密码
MySQL [(none)]> use test;
MySQL [test]> select * from userlist;
master : server1
[root@server1 ~]# yum install -y lsof
[root@server1 ~]# lsof -i :3306
再开启一个shell连接mysql
[kiosk@foundation66 Desktop]$ mysql -h 172.25.254.3 -u root -p
Enter password: #mysql登陆密码
MySQL [(none)]> use test;
MySQL [test]> select * from userlist;
[kiosk@foundation66 Desktop]$ mysql -h 172.25.254.3 -u root -p
Enter password: #mysql登陆密码
MySQL [(none)]> use test;
MySQL [test]> select * from userlist;
在连接mysql的shell里添加信息
MySQL [test]> insert into userlist values ('user4','666');
Query OK, 1 row affected (0.12 sec)
MySQL [test]> insert into userlist values ('user5','655566');
Query OK, 1 row affected (0.07 sec)
7、通过tcpdump抓取数据分析读写分离
[root@server3 ~]# yum install -y tcpdump
[root@server3 ~]# tcpdump -i eth0 port 3306