使用mysql-proxy实现mysql的读写分离

 前言:

  MySQL读写分离是指让master处理写操作,让slave处理读操作,非常适用于读操作量比较大的场景,可减轻master的压力。使用mysql-proxy实现mysql的读写分离,mysql-proxy实际上是作为后端mysql主从服务器的代理,它直接接受客户端的请求,对SQL语句进行分析,判断出是读操作还是写操作,然后分发至对应的mysql服务器上。mysql-proxy是官方提供的mysql中间件产品可以实现负载平衡,读写分离,failover等MySQL Proxy就是这么一个中间层代理,简单的说,MySQL Proxy就是一个连接池,负责将前台应用的连接请求转发给后台的数据库,并且通过使用lua脚本,可以实现复杂的连接控制和过滤,从而实现读写分离和负载平衡。对于应用来说,MySQL Proxy是完全透明的,应用则只需要连接到MySQL Proxy的监听端口即可。当然,这样proxy机器可能成为单点失效,但完全可以使用多个proxy机器做为冗余,在应用服务器的连接池配置中配置到多 个proxy的连接参数即可。

实验系统:CentOS 6.6_x86_64

实验前提:防火墙和selinux都关闭

实验说明:本实验共有4台主机,IP分配如拓扑

实验软件:mariadb-10.0.20  mysql-proxy-0.8.5-linux-el6-x86-64bit

下载地址:http://pan.baidu.com/s/1i3F5Pop

实验拓扑:

    

一、准备工作:

  1.将主机名称改为如下所示:

    

  2.将hosts文件添加如下内容:

    

  3.master、slave1和slave2安装mariadb:

tar xf mariadb-10.0.20-linux-x86_64.tar.gz  -C /usr/local/
cd /usr/local/
ln -sv mariadb-10.0.20-linux-x86_64 mysql
useradd -r mysql
mkdir -pv /mydata/data
chown -R mysql.mysql /mydata/data/
cd mysql/
chown -R root.mysql .
scripts/mysql_install_db --user=mysql --datadir=/mydata/data/
cp support-files/my-large.cnf /etc/my.cnf
cp support-files/mysql.server /etc/init.d/mysqld
chkconfig --add mysqld
chkconfig mysqld on

二、配置主从复制

  1.master上配置my.cnf:

[mysqld]
server-id       = 1
datadir = /mydata/data
log-bin = /mydata/data/master-bin
binlog_format = ROW
sync_binlog = 1                        //确保每次事务提交之前都能将二进制日志同步磁盘上

  2.slave1上配置my.cnf:

[mysqld]
#log-bin=mysql-bin
#binlog_format=mixed
server-id       = 2
datadir = /mydata/data
relay_log = /mydata/data/relay-log
read_only = 1
sync_master_info = 1                   //及时同步master文件
sync_relay_log = 1                     //及时同步relay-log文件
sync_relay_log_info = 1                //及时同步relay-log-info文件

  3.slave2上配置my.cnf:

[mysqld]
#log-bin=mysql-bin
#binlog_format=mixed
server-id       = 3
datadir = /mydata/data
relay_log = /mydata/data/relay-log
read_only = 1
sync_master_info = 1
sync_relay_log = 1
sync_relay_log_info = 1

  4.在master上创建复制用户:

service mysqld start
/usr/local/mysql/bin/mysql
------------------------------------------->
GRANT REPLICATION SLAVE,REPLICATION CLIENT ON *.* TO ‘slave‘@‘192.168.19.%‘ IDENTIFIED BY ‘123456‘;
FLUSH PRIVILEGES;

  5.在master上查看二进制日志位置:

SHOW MASTER LOGS;

    

  6.两台slave上操作:

CHANGE MASTER TO MASTER_HOST=‘master‘,MASTER_USER=‘slave‘,MASTER_PASSWORD=‘123456‘,MASTER_LOG_FILE=‘master-bin.000001‘,MASTER_LOG_POS=637;
START SLAVE;
SHOW SLAVE STATUS\G

    

三、安装mysql-proxy

  1.此实验中19.79为mysql-proxy服务器,所以软件安装在此主机上:

tar xf mysql-proxy-0.8.5-linux-el6-x86-64bit.tar.gz -C /usr/local/
cd /usr/local/
ln -sv mysql-proxy-0.8.5-linux-el6-x86-64bit mysql-proxy
useradd -r mysql-proxy

  2.提供服务脚本:

vim /etc/init.d/mysql-proxy
--------------------------------------------------------->
#!/bin/bash
#
# mysql-proxy This script starts and stops the mysql-proxy daemon
#
# chkconfig: - 78 30
# processname: mysql-proxy
# description: mysql-proxy is a proxy daemon for mysql

# Source function library.
. /etc/rc.d/init.d/functions

prog="/usr/local/mysql-proxy/bin/mysql-proxy"

# Source networking configuration.
if [ -f /etc/sysconfig/network ]; then
    . /etc/sysconfig/network
fi

# Check that networking is up.
[ ${NETWORKING} = "no" ] && exit 0

# Set default mysql-proxy configuration.
ADMIN_USER="admin"
ADMIN_PASSWD="admin"
ADMIN_LUA_SCRIPT="/usr/local/mysql-proxy/share/doc/mysql-proxy/admin.lua"
PROXY_OPTIONS="--daemon"
PROXY_PID=/var/run/mysql-proxy.pid
PROXY_USER="mysql-proxy"

# Source mysql-proxy configuration.
if [ -f /etc/sysconfig/mysql-proxy ]; then
    . /etc/sysconfig/mysql-proxy
fi

RETVAL=0

start() {
    echo -n $"Starting $prog: "
    daemon $prog $PROXY_OPTIONS --pid-file=$PROXY_PID --proxy-address="$PROXY_ADDRESS" --user=$PROXY_USER --admin-username="$ADMIN_USER" --admin-lua-script="$ADMIN_LUA_SCRIPT" --admin-password="$ADMIN_PASSWORD"
    RETVAL=$?
    echo
    if [ $RETVAL -eq 0 ]; then
        touch /var/lock/subsys/mysql-proxy
    fi
}

stop() {
    echo -n $"Stopping $prog: "
    killproc -p $PROXY_PID -d 3 $prog
    RETVAL=$?
    echo
    if [ $RETVAL -eq 0 ]; then
        rm -f /var/lock/subsys/mysql-proxy
        rm -f $PROXY_PID
    fi
}
# See how we were called.
case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        stop
        start
        ;;
    condrestart|try-restart)
        if status -p $PROXY_PIDFILE $prog >&/dev/null; then
            stop
            start
        fi
        ;;
    status)
        status -p $PROXY_PID $prog
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|reload|status|condrestart|try-restart}"
        RETVAL=1
        ;;
esac

exit $RETVAL<---------------------------------------------------------chmod +x /etc/init.d/mysql-proxychkconfig --add mysql-proxy

  3.为服务脚本提供配置文件:

vim /etc/sysconfig/mysql-proxy
--------------------------------------------------------->
# Options for mysql-proxy
ADMIN_USER="admin"
ADMIN_PASSWORD="admin"
ADMIN_ADDRESS=""
ADMIN_LUA_SCRIPT="/usr/local/mysql-proxy/share/doc/mysql-proxy/admin.lua"
PROXY_ADDRESS=""
PROXY_USER="mysql-proxy"
PROXY_OPTIONS="--daemon --log-level=info --log-use-syslog --plugins=proxy --plugins=admin --proxy-backend-addresses=192.168.19.66:3306 --proxy-read-only-backend-addresses=192.168.19.74:3306
 --proxy-read-only-backend-addresses=192.168.19.76:3306 --proxy-lua-script=/usr/local/mysql-proxy/share/doc/mysql-proxy/rw-splitting.lua"

//--daemon:以守护进程模式启动mysql-proxy//--proxy-backend-addresses:后端可读写的mysql服务器的地址和端口//--proxy-read-only-backend-addresses:后端只读mysql服务器的地址和端口//--proxy-lua-script:完成mysql代理功能的Lua脚本

  4.提供admin.lua文件:

vim /usr/local/mysql-proxy/share/doc/mysql-proxy/admin.lua
------------------------------------------------------------------------------>
--[[ $%BEGINLICENSE%$
 Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved.

 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License as
 published by the Free Software Foundation; version 2 of the
 License.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 02110-1301  USA

 $%ENDLICENSE%$ --]]

function set_error(errmsg)
proxy.response = {
type = proxy.MYSQLD_PACKET_ERR,
errmsg = errmsg or "error"
}
end

function read_query(packet)
if packet:byte() ~= proxy.COM_QUERY then
set_error("[admin] we only handle text-based queries (COM_QUERY)")
return proxy.PROXY_SEND_RESULT
end

local query = packet:sub(2)

local rows = { }
local fields = { }

if query:lower() == "select * from backends" then
fields = {
{ name = "backend_ndx",
 type = proxy.MYSQL_TYPE_LONG },

{ name = "address",
 type = proxy.MYSQL_TYPE_STRING },
{ name = "state",
 type = proxy.MYSQL_TYPE_STRING },
{ name = "type",
 type = proxy.MYSQL_TYPE_STRING },
{ name = "uuid",
 type = proxy.MYSQL_TYPE_STRING },
{ name = "connected_clients",
 type = proxy.MYSQL_TYPE_LONG },
}

for i = 1, #proxy.global.backends do
local states = {
"unknown",
"up",
"down"
}
local types = {
"unknown",
"rw",
"ro"
}
local b = proxy.global.backends[i]

rows[#rows + 1] = {
i,
b.dst.name,          -- configured backend address
states[b.state + 1], -- the C-id is pushed down starting at 0
types[b.type + 1],   -- the C-id is pushed down starting at 0
b.uuid,              -- the MySQL Server‘s UUID if it is managed
b.connected_clients  -- currently connected clients
}
end
elseif query:lower() == "select * from help" then
fields = {
{ name = "command",
 type = proxy.MYSQL_TYPE_STRING },
{ name = "description",
 type = proxy.MYSQL_TYPE_STRING },
}
rows[#rows + 1] = { "SELECT * FROM help", "shows this help" }
rows[#rows + 1] = { "SELECT * FROM backends", "lists the backends and their state" }
else
set_error("use ‘SELECT * FROM help‘ to see the supported commands")
return proxy.PROXY_SEND_RESULT
end

proxy.response = {
type = proxy.MYSQLD_PACKET_OK,
resultset = {
fields = fields,
rows = rows
}
}
return proxy.PROXY_SEND_RESULT
end

  5.为了使实验结果更明显,编辑rw-splitting.lua文件中的其中2个数值:

vim /usr/local/mysql-proxy/share/doc/mysql-proxy/rw-splitting.lua
--------------------------------------------------------------------------->
if not proxy.global.config.rwsplit then
        proxy.global.config.rwsplit = {
                min_idle_connections = 1,     //默认为4
                max_idle_connections = 1,    //默认为8

                is_debug = false
        }
end          //mysql-proxy会检测客户端连接,当连接没有超过min_idle_connections预设值时, 不会进行读写分离, 即查询操作会发生到Master上。

5.启动mysql-proxy:

service mysql-proxy start
ss -tnlp                      //查看端口

    

  6.连接测试:

yum -y install mysql                               //如果没有mysql客户端的话执行此步
mysql -uadmin -padmin -h192.168.19.79 --port=4041
------------------------------------------------------------>
SELECT * FROM backends;
+-------------+--------------------+---------+------+------+-------------------+
| backend_ndx | address            | state   | type | uuid | connected_clients |
+-------------+--------------------+---------+------+------+-------------------+
|           1 | 192.168.19.66:3306 | unknown | rw   | NULL |                 0 |
|           2 | 192.168.19.74:3306 | unknown | ro   | NULL |                 0 |
|           3 | 192.168.19.76:3306 | unknown | ro   | NULL |                 0 |
+-------------+--------------------+---------+------+------+-------------------+

四、读写分离测试:

  1.在master上创建测试用户:

GRANT ALL ON *.* TO ‘jason‘@‘192.168.19.%‘ IDENTIFIED BY ‘123456‘;
FLUSH PRIVILEGES;

  2.分别在三台mariadb服务器上抓包:

    master:

tcpdump -i eth0 -nn -XX ip dst 192.168.19.66 and tcp dst port 3306      //目标是19.66并且端口是3306

    slave1:

tcpdump -i eth0 -nn -XX ip dst 192.168.19.74 and tcp dst port 3306

    slave2:

tcpdump -i eth0 -nn -XX ip dst 192.168.19.76 and tcp dst port 3306

  3.mysql-proxy上进行数据库操作:

mysql -ujason -p123456 -h192.168.19.79
------------------------------------------------->
CREATE DATABASE hello;USE mysql;SELECT * FROM user;             //可以用额外的主机多执行几次

    在master上的抓包信息:

    

    在slave上的抓包信息:

    

    

  4.查看状态,在proxy上操作,可以看到状态全部为up:

mysql -uadmin -padmin -h192.168.19.79 --port=4041
------------------------------------------------------------->
SELECT * FROM backends;
+-------------+--------------------+-------+------+------+-------------------+
| backend_ndx | address            | state | type | uuid | connected_clients |
+-------------+--------------------+-------+------+------+-------------------+
|           1 | 192.168.19.66:3306 | up    | rw   | NULL |                 0 |
|           2 | 192.168.19.74:3306 | up    | ro   | NULL |                 0 |
|           3 | 192.168.19.76:3306 | up    | ro   | NULL |                 0 |
+-------------+--------------------+-------+------+------+-------------------+

五、拓展实验

  1.在proxy上安装httpd和php:

yum install httpd php php-mysql
service httpd start

  2.让httpd可以支持index.php首页,然后放入wordpress页面文件,创建wordpress数据库并安装:

    

  3.安装完后修改wordpress的配置文件,将master地址改为proxy的:

vim /var/www/html/wp-config.php

    

  4.访问测试并抓包:

    master:

    

    slave:

    

    

转载链接:https://www.cnblogs.com/tae44/p/4701226.html

原文地址:https://www.cnblogs.com/xiaoyuxixi/p/12075353.html

时间: 2024-10-09 11:45:48

使用mysql-proxy实现mysql的读写分离的相关文章

使用mysql proxy对数据库进行读写分离

服务器安排如下: 192.168.100.128 主 192.168.100.129 从 192.168.100.130 mysql-proxy 1.在100.130中下载安装mysql-proxy tar -zxvf mysql-proxy-0.8.5-linux-el6-x86-64bit.tar.gz cp mysql-proxy-0.8.5-linux-el6-x86-64bit /usr/local/mysql-proxy 2.配置环境变量 LUA_PATH="/usr/local/m

MySQL Proxy实现数据的读写分离

做MySQL读写分离实验之前,先要搭建MySQL主从复制,可以参考我之前的两篇文章: MySQL主从配置:http://msiyuetian.blog.51cto.com/8637744/1697288 部署搭建分层次LAMP架构(最后一章节):http://msiyuetian.blog.51cto.com/8637744/1740236 实现了主从复制后,下面我们进行读写分离的安装与配置.环境说明: Linux发行版本:centos 6.7 x86_64 (三台) Hostname IP 备

Mysql主从配置,实现读写分离

大型网站为了软解大量的并发访问,除了在网站实现分布式负载均衡,远远不够.到了数据业务层.数据访问层,如果还是传统的数据结构,或者只是单单靠一台服务器扛,如此多的数据库连接操作,数据库必然会崩溃,数据丢失的话,后果更是 不堪设想.这时候,我们会考虑如何减少数据库的联接,一方面采用优秀的代码框架,进行代码的优化,采用优秀的数据缓存技术如:memcached,如果资金丰厚的话,必然会想到假设服务器群,来分担主数据库的压力.Ok切入今天微博主题,利用MySQL主从配置,实现读写分离,减轻数据库压力.这种

MySQL/MariaDB基于MMM实现读写分离及高可用

前言 MMM(Master-Master replication managerfor Mysql,Mysql主主复制管理器)是一套灵活的脚本程序,基于perl实现,用来对mysql replication进行监控和故障迁移,并能管理mysql Master-Master复制的配置(同一时间只有一个节点是可写的). MMM 优缺点 优点:高可用性,扩展性好,出现故障自动切换,对于主主同步,在同一时间只提供一台数据库写操作,保证的数据的一致性. 缺点:Monitor节点是单点,可以结合Keepal

高可用架构篇--MyCat在MySQL主从复制基础上实现读写分离

点击链接加入群[Dubbo技术交流2群]:https://jq.qq.com/?_wv=1027&k=46DcDFI 一.环境 操作系统:CentOS-6.6-x86_64-bin-DVD1.iso JDK版本:jdk1.7.0_45 MyCat版本:Mycat-server-1.4-release-20151019230038-linux.tar.gz MyCat节点IP:192.168.1.203      主机名:edu-mycat-01  主机配置:4核CPU.4G内存 MySQL版本:

MySQL Proxy 实现 MySQL 读写分离提高并发负载

工作拓扑: MySQL Proxy有一项强大功能是实现"读写分离",基本原理是让主数据库处理写方面事务,让从库处理SELECT查询. Amoeba for MySQL是一款优秀的中间件软件,同样可以实现读写分离,负载均衡等功能,并且稳定性也高于MySQL Proxy,有兴趣的可以测试一下. 环境描述: 操作系统:CentOS6.3_x64 主服务器Master:192.168.0.202 从服务器Slave:192.168.0.203 调度服务器MySQL-Proxy:192.168.

mysql数据库多种备份及读写分离搭建

数据库的版本 1.社区版 2.企业版 3.集群版 数据库的安装 1.     专用软件包管理器(二进制) deb .rpm等 mysql                 MySQL客户端程序和共享库 mysql-server            MySQL服务器需要的相关程序 2.     源代码软件包(编译安装) configure.cmake 数据库常用的配置选项 -DCMAKE_INSTALL_PREFIX=/usr/local/mysql    ----指定残可安装路径(默认的就是/u

mysql集群:主从服务器读写分离

mysql集群架构方式很多,根据不同的需求做不一样的架构,简单一点的就是mysql的replication,也就是Mysql的复制功能,模式有:master-slaves,master-slaves-slaves,master-master-slaves等可以有多个分层,那么现在我所要说的是master-slaves的模式(其他的模式原理基本都一样),然后再通过mysql官方提供的Mysql-proxy实现读写分离,达到的效果. 环境: 主机::192.168.1.109,slave1:192.

MySQL和MariaDB 备份 主从 读写分离

查询缓存: 如何判断是否命中: 通过查询语句的哈希值判断:哈希值考虑的因素包括 查询本身.要查询的数据库.客户端使用协议版本,... 查询语句任何字符上的不同,都会导致缓存不能命中: 哪此查询可能不会被缓存? 查询中包含UDF.存储函数.用户自定义变量.临时表.mysql库中系统表.或者包含列级权限的表.有着不确定值的函数(Now()); 查询缓存相关的服务器变量: query_cache_min_res_unit: 查询缓存中内存块的最小分配单位: 较小值会减少浪费,但会导致更频繁的内存分配操

Mysql之主从模式、读写分离概念

MySQL主从架构复制: 在主server上每次进行可能引起数据变化的操作都要先记录到二进制文件中,并将数据同步到主server的磁盘上,与此同时还要通过端口(3306)将二进制日志发送到从server上,在从server上,从server会先将接受的二进制日志保存为中继日志(relay log),在从中继日志中进行读取,重新执行一遍操作,进行数据的复制 但一般来说,如果主server有多个cpu,当数据量变化很频繁时,可能会在每个cpu上都运行一个事务,而注server只能一个个的记录入二进制