环境

nameIPSERVER
Master172.16.0.14Shell
Slave172.16.0.19Mysql
mysql-proxy172.16.0.1mysql-proxy
Master和Slave 配置主从复制
全部机器关闭selinux和防火墙

安装 mysql-proxy

wget https://downloads.mysql.com/archives/get/p/21/file/mysql-proxy-0.8.5-linux-glibc2.3-x86-64bit.tar.gz
tar zxf mysql-proxy-0.8.5-linux-glibc2.3-x86-64bit.tar.gz 
mv mysql-proxy-0.8.5-linux-glibc2.3-x86-64bit /usr/local/mysql-proxy

配置 mysql-proxy

cd /usr/local/mysql-proxy
mkdir lua    #创建脚本存放目录
mkdir logs   #创建日志目录
cp share/doc/mysql-proxy/rw-splitting.lua ./lua   #复制读写分离配置文件
cp share/doc/mysql-proxy/admin-sql.lua ./lua      #复制管理脚本

编辑读写分离配置文件

vim /usr/local/mysql-proxy/lua/rw-splitting.lua
if not proxy.global.config.rwsplit then
    proxy.global.config.rwsplit = {
        min_idle_connections = 1,   #默认超过1个连接数时,才开始读写分离,默认4
        max_idle_connections = 1,   #默认8

        is_debug = false
    }
end

创建配置文件

--注意配置文件里面不要有任何注释和空格,否则会启动失败
vim /etc/mysql-proxy.cnf
[mysql-proxy]
user=root       #运行mysql-proxy的用户
admin-username=root    #主从mysql共有的用户
admin-password=123456  #用户的密码
proxy-address=172.16.0.1:404  #指定mysql-proxy 运行时监听的IP和端口
proxy-read-only-backend-addresses=172.16.0.19  #指定从Slave读取数据
proxy-backend-addresses=172.16.0.14            #指定从Master写入数据
proxy-lua-script=/usr/local/mysql-proxy/lua/rw-splitting.lua  #指定读写分离配置文件位置
admin-lua-script=/usr/local/mysql-proxy/lua/admin-sql.lua  #指定管理脚本
log-file=/usr/local/mysql-proxy/logs/mysql-proxy.log  #日志
log-level=info  #定义log日志级别,由高到低分别有(error|warning|info|message|debug)
daemon=true     #以守护进程方式运行
keepalive=true  #mysql-proxy崩溃时,尝试重启

启动 mysql-proxy

/usr/local/mysql-proxy/bin/mysql-proxy --defaults-file=/etc/mysql-proxy.cnf
root@linux:/# netstat -tunpl|grep 404
tcp        0      0 172.16.0.1:404          0.0.0.0:*               LISTEN      29705/mysql-proxy   

验证读写分离

--登陆mysql-proxy,插入数据
[root@localhost ~]# mysql -uroot -p123456 -h172.16.0.1 -P404
mysql> create database db;
mysql> use db
mysql> insert into db values(1,'END',123456);
mysql> insert into db values(2,'TOM',123456);

--在mysql-proxy 查看数据
mysql> select * from db.db;
+------+------+--------+
| id   | name | passwd |
+------+------+--------+
|    1 | END  | 123456 |
|    2 | TOM  | 123456 |
+------+------+--------+
2 rows in set (0.00 sec)

--登录Slave 的数据库查看是否是否同步
root@linux:/# mysql -uroot -p123456 -h172.16.0.19 -e "select * from db.db;"
+------+------+--------+
| id   | name | passwd |
+------+------+--------+
|    1 | END  | 123456 |
|    2 | TOM  | 123456 |
+------+------+--------+
Last modification:February 24th, 2022 at 07:39 am