目录
Connection Pooling
Read/Write Splitting
Possible extensions
Known Problems
Next Steps
首页 数据库 mysql教程 MySQL Proxy learns R/W Splitting

MySQL Proxy learns R/W Splitting

Jun 07, 2016 pm 03:26 PM
mysql proxy t

The trunk version of the MySQL Proxy 0.6.0 just learnt about changing backends within running connection. It is now up to lua-script to decide which backend shall be used to send requests too. We wrote a complete tutorial which covers ever

The trunk version of the MySQL Proxy 0.6.0 just learnt about changing backends within running connection. It is now up to lua-script to decide which backend shall be used to send requests too.

We wrote a complete tutorial which covers everything from:

  • building and maintaining a connection pool with high and low water marks
  • transparent authentication (no extra auth against the proxy)
  • deciding on Query Level which backend to use

and implement a transparent read/write splitter which sends all non-transactional Queries to the slaves and the rest to the master.

MySQL Proxy learns R/W Splitting

As the splitting is in the hands of the lua-scripting level you can use the same to implement sharding or other rules to route traffic on statement level.

Connection Pooling

For R/W Splitting we need a connection pooling. We only switch to another backend if we already have a authenticated connection open to that backend.

The MySQL protocol first does a challenge-response handshake. When we enter the query/result stage it is too late to authenticate new connections. We have to make sure that we have enough open connections to operate nicely.

MySQL Proxy learns R/W Splitting

In the keepalive tutorial we spend quite some code on connection management. The whole connect_servers() function is only to create new connections for all pools.

  1. create one connection to each backend
  2. create new connections until we reach min-idle-connections
  3. if the two above conditions are met, use a connection from the pool

Let's take a glimpse at the code:

<code>--- config
--
-- connection pool
local min_idle_connections = 4
local max_idle_connections = 8

---
-- get a connection to a backend
--
-- as long as we don't have enough connections in the pool, create new connections
--
function connect_server()
  -- make sure that we connect to each backend at least ones to
  -- keep the connections to the servers alive
  --
  -- on read_query we can switch the backends again to another backend

  local least_idle_conns_ndx = 0
  local least_idle_conns = 0

  for i = 1, #proxy.servers do
    local s = proxy.servers[i]

    if s.state ~= proxy.BACKEND_STATE_DOWN then
      -- try to connect to each backend once at least
      if s.idling_connections == 0 then
        proxy.connection.backend_ndx = i
        return
      end

      -- try to open at least min_idle_connections
      if least_idle_conns_ndx == 0 or
         ( s.idling_connections  0 then
    proxy.connection.backend_ndx = least_idle_conns_ndx
  end

  if proxy.connection.backend_ndx > 0 and
     proxy.servers[proxy.connection.backend_ndx].idling_connections >= min_idle_connections then
    -- we have 4 idling connections in the pool, that's good enough

    return proxy.PROXY_IGNORE_RESULT
  end

  -- open a new connection
end
</code>
登录后复制

The real trick is in

<code>---
-- put the authed connection into the connection pool
function read_auth_result(packet)
  -- disconnect from the server
  proxy.connection.backend_ndx = 0
end
</code>
登录后复制

The proxy.connection.backend_ndx = 0 we disconnect us from the current backend (lua starts indexing at index 1, 0 is out of bounds). If a second connection comes in now it can use this authed connection too as it is in the pool, idling.

By setting proxy.connection.backend_ndx you control which backend is used to send your packets too. A backend is defined as a entry of the proxy.servers table. Each connection has (zero or) one backend. The backends all have a address, a type (RW or RO) and a state (UP or DOWN).

As we also might have to many open connections in the pool we close them on shutdown again if necessary:

<code>---
-- close the connections if we have enough connections in the pool
--
-- @return nil - close connection
--         IGNORE_RESULT - store connection in the pool
function disconnect_client()
  if proxy.connection.backend_ndx == 0 then
    -- currently we don't have a server backend assigned
    --
    -- pick a server which has too many idling connections and close one
    for i = 1, #proxy.servers do
      local s = proxy.servers[i]

      if s.state ~= proxy.BACKEND_STATE_DOWN and
         s.idling_connections > max_idle_connections then
        -- try to disconnect a backend
        proxy.connection.backend_ndx = i
        return
      end
    end
  end
end
</code>
登录后复制

We only search for a backend which has to many open idling connections and use it before we enter the default behaviour of disconnect_client: shutdown the server connection. if proxy.connection.backend_ndx == 0 then is the "we don't have backend associated right now". We already saw this in read_auth_result.

Read/Write Splitting

That is our maintainance of the pool. connect_server() adds new auth'ed connections to the pool, disconnect_client() closes them again. The read/write splitting is part of the query/result cycle:

<code>-- read/write splitting
function read_query( packet )
  if packet:byte() == proxy.COM_QUIT then
    -- don't send COM_QUIT to the backend. We manage the connection
    -- in all aspects.
    proxy.response = {
      type = proxy.MYSQLD_PACKET_ERR,
      errmsg = "ignored the COM_QUIT"
    }

    return proxy.PROXY_SEND_RESULT
  end

  -- as we switch between different connenctions we have to make sure that
  -- we use always the same DB
  if packet:byte() == proxy.COM_INIT_DB then
    -- default_db is connection global
    default_db = packet:sub(2)
  end

  if proxy.connection.backend_ndx == 0 then
    -- we don't have a backend right now
    --
    -- let's pick a master as a good default
    for i = 1, #proxy.servers do
      local s = proxy.servers[i]

      if s.idling_connections > 0 and
         s.state ~= proxy.BACKEND_STATE_DOWN and
         s.type == proxy.BACKEND_TYPE_RW then
        proxy.connection.backend_ndx = i
        break
      end
    end
  end

  if packet:byte() == proxy.COM_QUERY and default_db then
    -- how can I know the db of the server connection ?
    proxy.queries:append(2, string.char(proxy.COM_INIT_DB) .. default_db)
  end
  proxy.queries:append(1, packet)
</code>
登录后复制

Up to now it is only making sure that we behave nicely:

  • don't forward COM_QUIT to the backend as he will close the connection on us
  • intercept the COM_INIT_DB to know which DB the client wants to work on. If we switch to another backend we have to make sure the same DB is used.

The read/write splitting is now following a simple rule:

  • send all non-transactional SELECTs to a slave
  • everything else goes to the master

We are still in read_query()

<code>  -- read/write splitting
  --
  -- send all non-transactional SELECTs to a slave
  if is_in_transaction == 0 and
     packet:byte() == proxy.COM_QUERY and
     packet:sub(2, 7) == "SELECT" then
    local max_conns = -1
    local max_conns_ndx = 0

    for i = 1, #proxy.servers do
      local s = proxy.servers[i]

      -- pick a slave which has some idling connections
      if s.type == proxy.BACKEND_TYPE_RO and
         s.idling_connections > 0 then
        if max_conns == -1 or
           s.connected_clients  0 then
      proxy.connection.backend_ndx = max_conns_ndx
    end
  else
    -- send to master
  end

  return proxy.PROXY_SEND_QUERY
end
</code>
登录后复制

If we found a slave host which has a idling connection we pick it. If all slaves are busy or down, we just send the query to the master.

As soon as we don't need this connection anymore give it backend to the pool:

<code>---
-- as long as we are in a transaction keep the connection
-- otherwise release it so another client can use it
function read_query_result( inj )
  local res      = assert(inj.resultset)
  local flags    = res.flags

  if inj.id ~= 1 then
    -- ignore the result of the USE <default_db>
    return proxy.PROXY_IGNORE_RESULT
  end
  is_in_transaction = flags.in_trans

  if is_in_transaction == 0 then
    -- release the backend
    proxy.connection.backend_ndx = 0
  end
end
</default_db></code>
登录后复制

The MySQL Protocol is nice and offers us a in-transaction-flag. This operates on the state of the transaction and works across all engines. If you want to make sure that several statements go to the same backend, open a transaction with BEGIN. No matter which storage engine you use.

Possible extensions

While we are here in this div of the code think about another use case:

  • if the master is down, ban all writing queries and only allow reading selects against the slaves.

It keeps your site up and running even if your master is gone. You only have to handle errors on write-statements and transactions.

Known Problems

We might have a race-condition that idling connection closes before we can use it. In that case we are in trouble right now and will close the connection to the client.

We have to add queuing of connections and awaking them up when the connection becomes available again to handle this later.

Next Steps

Testing, testing, testing.

<code>$ mysql-proxy /
    --proxy-backend-addresses=10.0.0.1:3306 /
    --proxy-read-only-backend-addresses=10.0.0.10:3306 /
    --proxy-read-only-backend-addresses=10.0.0.12:3306 /
    --proxy-lua-script=examples/tutorial-keepalive.lua
</code>
登录后复制

The above code works for my tests, but I don't have any real load. Nor can I create all the error-cases you have in your real-life setups. Please send all your comments, concerns and ideas to the MySQL Proxy forum.

Another upcoming step is externalizing all the load-balancer code and move it into modules to make the code easier to understand and reuseable.

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

phpmyadmin怎么打开 phpmyadmin怎么打开 Apr 10, 2025 pm 10:51 PM

可以通过以下步骤打开 phpMyAdmin:1. 登录网站控制面板;2. 找到并点击 phpMyAdmin 图标;3. 输入 MySQL 凭据;4. 点击 "登录"。

MySQL:世界上最受欢迎的数据库的简介 MySQL:世界上最受欢迎的数据库的简介 Apr 12, 2025 am 12:18 AM

MySQL是一种开源的关系型数据库管理系统,主要用于快速、可靠地存储和检索数据。其工作原理包括客户端请求、查询解析、执行查询和返回结果。使用示例包括创建表、插入和查询数据,以及高级功能如JOIN操作。常见错误涉及SQL语法、数据类型和权限问题,优化建议包括使用索引、优化查询和分表分区。

MySQL的位置:数据库和编程 MySQL的位置:数据库和编程 Apr 13, 2025 am 12:18 AM

MySQL在数据库和编程中的地位非常重要,它是一个开源的关系型数据库管理系统,广泛应用于各种应用场景。1)MySQL提供高效的数据存储、组织和检索功能,支持Web、移动和企业级系统。2)它使用客户端-服务器架构,支持多种存储引擎和索引优化。3)基本用法包括创建表和插入数据,高级用法涉及多表JOIN和复杂查询。4)常见问题如SQL语法错误和性能问题可以通过EXPLAIN命令和慢查询日志调试。5)性能优化方法包括合理使用索引、优化查询和使用缓存,最佳实践包括使用事务和PreparedStatemen

为什么要使用mysql?利益和优势 为什么要使用mysql?利益和优势 Apr 12, 2025 am 12:17 AM

选择MySQL的原因是其性能、可靠性、易用性和社区支持。1.MySQL提供高效的数据存储和检索功能,支持多种数据类型和高级查询操作。2.采用客户端-服务器架构和多种存储引擎,支持事务和查询优化。3.易于使用,支持多种操作系统和编程语言。4.拥有强大的社区支持,提供丰富的资源和解决方案。

apache怎么连接数据库 apache怎么连接数据库 Apr 13, 2025 pm 01:03 PM

Apache 连接数据库需要以下步骤:安装数据库驱动程序。配置 web.xml 文件以创建连接池。创建 JDBC 数据源,指定连接设置。从 Java 代码中使用 JDBC API 访问数据库,包括获取连接、创建语句、绑定参数、执行查询或更新以及处理结果。

docker怎么启动mysql docker怎么启动mysql Apr 15, 2025 pm 12:09 PM

在 Docker 中启动 MySQL 的过程包含以下步骤:拉取 MySQL 镜像创建并启动容器,设置根用户密码并映射端口验证连接创建数据库和用户授予对数据库的所有权限

centos安装mysql centos安装mysql Apr 14, 2025 pm 08:09 PM

在 CentOS 上安装 MySQL 涉及以下步骤:添加合适的 MySQL yum 源。执行 yum install mysql-server 命令以安装 MySQL 服务器。使用 mysql_secure_installation 命令进行安全设置,例如设置 root 用户密码。根据需要自定义 MySQL 配置文件。调整 MySQL 参数和优化数据库以提升性能。

centos7如何安装mysql centos7如何安装mysql Apr 14, 2025 pm 08:30 PM

优雅安装 MySQL 的关键在于添加 MySQL 官方仓库。具体步骤如下:下载 MySQL 官方 GPG 密钥,防止钓鱼攻击。添加 MySQL 仓库文件:rpm -Uvh https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm更新 yum 仓库缓存:yum update安装 MySQL:yum install mysql-server启动 MySQL 服务:systemctl start mysqld设置开机自启动

See all articles