Table des matières
Connection Pooling
Read/Write Splitting
Possible extensions
Known Problems
Next Steps
Maison base de données tutoriel 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>
Copier après la connexion

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>
Copier après la connexion

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>
Copier après la connexion

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>
Copier après la connexion

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>
Copier après la connexion

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>
Copier après la connexion

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>
Copier après la connexion

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.

Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn

Outils d'IA chauds

Undresser.AI Undress

Undresser.AI Undress

Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover

AI Clothes Remover

Outil d'IA en ligne pour supprimer les vêtements des photos.

Undress AI Tool

Undress AI Tool

Images de déshabillage gratuites

Clothoff.io

Clothoff.io

Dissolvant de vêtements AI

Video Face Swap

Video Face Swap

Échangez les visages dans n'importe quelle vidéo sans effort grâce à notre outil d'échange de visage AI entièrement gratuit !

Outils chauds

Bloc-notes++7.3.1

Bloc-notes++7.3.1

Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise

SublimeText3 version chinoise

Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1

Envoyer Studio 13.0.1

Puissant environnement de développement intégré PHP

Dreamweaver CS6

Dreamweaver CS6

Outils de développement Web visuel

SublimeText3 version Mac

SublimeText3 version Mac

Logiciel d'édition de code au niveau de Dieu (SublimeText3)

Comment ouvrir phpmyadmin Comment ouvrir phpmyadmin Apr 10, 2025 pm 10:51 PM

Vous pouvez ouvrir PHPMYADMIN via les étapes suivantes: 1. Connectez-vous au panneau de configuration du site Web; 2. Trouvez et cliquez sur l'icône PHPMYADMIN; 3. Entrez les informations d'identification MySQL; 4. Cliquez sur "Connexion".

MySQL: une introduction à la base de données la plus populaire au monde MySQL: une introduction à la base de données la plus populaire au monde Apr 12, 2025 am 12:18 AM

MySQL est un système de gestion de la base de données relationnel open source, principalement utilisé pour stocker et récupérer les données rapidement et de manière fiable. Son principe de travail comprend les demandes des clients, la résolution de requête, l'exécution des requêtes et les résultats de retour. Des exemples d'utilisation comprennent la création de tables, l'insertion et la question des données et les fonctionnalités avancées telles que les opérations de jointure. Les erreurs communes impliquent la syntaxe SQL, les types de données et les autorisations, et les suggestions d'optimisation incluent l'utilisation d'index, les requêtes optimisées et la partition de tables.

Place de MySQL: bases de données et programmation Place de MySQL: bases de données et programmation Apr 13, 2025 am 12:18 AM

La position de MySQL dans les bases de données et la programmation est très importante. Il s'agit d'un système de gestion de base de données relationnel open source qui est largement utilisé dans divers scénarios d'application. 1) MySQL fournit des fonctions efficaces de stockage de données, d'organisation et de récupération, en prenant en charge les systèmes Web, mobiles et de niveau d'entreprise. 2) Il utilise une architecture client-serveur, prend en charge plusieurs moteurs de stockage et optimisation d'index. 3) Les usages de base incluent la création de tables et l'insertion de données, et les usages avancés impliquent des jointures multiples et des requêtes complexes. 4) Des questions fréquemment posées telles que les erreurs de syntaxe SQL et les problèmes de performances peuvent être déboguées via la commande Explication et le journal de requête lente. 5) Les méthodes d'optimisation des performances comprennent l'utilisation rationnelle des indices, la requête optimisée et l'utilisation des caches. Les meilleures pratiques incluent l'utilisation des transactions et des acteurs préparés

Pourquoi utiliser MySQL? Avantages et avantages Pourquoi utiliser MySQL? Avantages et avantages Apr 12, 2025 am 12:17 AM

MySQL est choisi pour ses performances, sa fiabilité, sa facilité d'utilisation et son soutien communautaire. 1.MySQL fournit des fonctions de stockage et de récupération de données efficaces, prenant en charge plusieurs types de données et opérations de requête avancées. 2. Adoptez l'architecture client-serveur et plusieurs moteurs de stockage pour prendre en charge l'optimisation des transactions et des requêtes. 3. Facile à utiliser, prend en charge une variété de systèmes d'exploitation et de langages de programmation. 4. Avoir un solide soutien communautaire et fournir des ressources et des solutions riches.

Comment se connecter à la base de données d'Apache Comment se connecter à la base de données d'Apache Apr 13, 2025 pm 01:03 PM

Apache se connecte à une base de données nécessite les étapes suivantes: Installez le pilote de base de données. Configurez le fichier web.xml pour créer un pool de connexion. Créez une source de données JDBC et spécifiez les paramètres de connexion. Utilisez l'API JDBC pour accéder à la base de données à partir du code Java, y compris l'obtention de connexions, la création d'instructions, les paramètres de liaison, l'exécution de requêtes ou de mises à jour et de traitement des résultats.

Comment démarrer MySQL par Docker Comment démarrer MySQL par Docker Apr 15, 2025 pm 12:09 PM

Le processus de démarrage de MySQL dans Docker se compose des étapes suivantes: Tirez l'image MySQL pour créer et démarrer le conteneur, définir le mot de passe de l'utilisateur racine et mapper la connexion de vérification du port Créez la base de données et l'utilisateur accorde toutes les autorisations sur la base de données

CentOS installe MySQL CentOS installe MySQL Apr 14, 2025 pm 08:09 PM

L'installation de MySQL sur CENTOS implique les étapes suivantes: Ajout de la source MySQL YUM appropriée. Exécutez la commande YUM Install MySQL-Server pour installer le serveur MySQL. Utilisez la commande mysql_secure_installation pour créer des paramètres de sécurité, tels que la définition du mot de passe de l'utilisateur racine. Personnalisez le fichier de configuration MySQL selon les besoins. Écoutez les paramètres MySQL et optimisez les bases de données pour les performances.

Comment installer MySQL dans CentOS7 Comment installer MySQL dans CentOS7 Apr 14, 2025 pm 08:30 PM

La clé de l'installation de MySQL est d'élégance pour ajouter le référentiel MySQL officiel. Les étapes spécifiques sont les suivantes: Téléchargez la clé GPG officielle MySQL pour empêcher les attaques de phishing. Ajouter un fichier de référentiel MySQL: RPM -UVH https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm Mise à jour du référentiel Cache: Yum Update Installation Mysql: Yum install install install starting starting mysql Service: SystemCTL start start mysqld starger bugo boartup Service mysql Service: SystemCTL start start mysqld starger bugo bo onthing staring Service mysql Service: SystemCTL Start Start MySQLD Set Out Up Boaching Staring Service MySQL Service: SystemCTL Start Start MysQL

See all articles