四、 配置数据库读写分离,由MySQL proxy代理完成
1、 配置mysql proxy,根据需要下载32位或64位
wget http://cdn.mysql.com/Downloads/MySQL-Proxy/mysql-proxy-0.8.3-linux-glibc2.3-x86-32bit.tar.gz
wget http://cdn.mysql.com/Downloads/MySQL-Proxy/mysql-proxy-0.8.3-linux-glibc2.3-x86-64bit.tar.gz
解压mysql proxy
tar –zxvf mysql-proxy-0.8.3-linux-glibc2.3-x86-32bit.tar.gz
cp –r mysql-proxy-0.8.3-linux-glibc2.3-x86-32bit /usr/local/mysql-proxy
2、 创建mysql proxy配置文件,具体参数可查看/usr/local/mysql-proxy/bin/mysql-proxy –help-all
vi /etc/mysql-proxy.cnf
[mysql-proxy]
user=root #指定mysql-proxy运行用户
proxy-address=192.168.128.5:4040 #mysql-proxy运行运行ip和端口号
proxy-read-only-backend-addresses=192.168.128.9:3306 #读操作数据库地址
proxy-read-only-backend-addresses=192.168.128.10:3306
proxy-backend-addresses=192.168.128.8:3306 #写操作数据库地址
proxy-lua-script=/usr/local/mysql-proxy/scripts/rw-splitting.lua #读写分离配置文件路径
log-file=/usr/local/mysql-proxy/log/mysql-proxy.log #日志文件存放路径
log-level=debug
daemon=true #以守护进程方式运行
keepalive=true #mysql-proxy进程假死后自动重启
3、 创建日志存放目录
mkdir /usr/local/mysql-proxy/log
4、 复制读写分离配置文件
mkdir /usr/local/mysql-proxy/scripts
cp /usr/local/mysql-proxy/share/doc/mysql-proxy/rw-splitting.lua /usr/local/mysql-proxy/scripts
5、 修改读写分离配置文件,默认达到4个连接才进行读写分离
vi /usr/local/mysql-proxy/scripts/rw-splitting.lua
if not proxy.global.config.rwsplit then
proxy.global.config.rwsplit = {
min_idle_connections = 1, #默认4,改为1
max_idle_connections = 1, #默认8,改为1
is_debug = false
}
end
6、 修改mysql-proxy.cnf权限
chmod 660 /etc/mysql-proxy.cnf
7、 启动mysql proxy
/usr/local/mysql-proxy/bin/mysql-proxy --defaults-file=/etc/mysql-proxy.cnf
8、 创建用于读写分离数据库连接账户
登陆主服务器,创建用户
mysql > GRANT ALL PRIVILEGES ON *.* TO "proxy"@"192.168.128.5" IDENTIFIED BY 'proxy' WITH GRANT OPTION;
9、 测试读写分离
从客户端登陆proxy代理,进行测试
[root@mysql ~]# mysql -u test -h192.168.128.5 -p -P4040
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 61
Server version: 5.1.61-log Source distribution
Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| db1 |
| db2 |
| db3 |
| mysql |
| zabbix |
+--------------------+
6 rows in set (0.16 sec)
查询为128.6数据库
关闭128.6mysql,在查询
mysql> show databases;
ERROR 2006 (HY000): MySQL server has gone away
No connection. Trying to reconnect...
Connection id: 199
Current database: *** NONE ***
+--------------------+
| Database |
+--------------------+
| information_schema |
| db1 |
| db2 |
| db3 |
| mysql |
| performance_schema |
| test |
| wikidb |
+--------------------+
8 rows in set (0.02 sec)
查询内容为128.7数据库