목차
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 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

PHP의 빅데이터 구조 처리 능력 PHP의 빅데이터 구조 처리 능력 May 08, 2024 am 10:24 AM

빅 데이터 구조 처리 기술: 청킹(Chunking): 데이터 세트를 분할하고 청크로 처리하여 메모리 소비를 줄입니다. 생성기: 전체 데이터 세트를 로드하지 않고 데이터 항목을 하나씩 생성하므로 무제한 데이터 세트에 적합합니다. 스트리밍: 파일을 읽거나 결과를 한 줄씩 쿼리하므로 대용량 파일이나 원격 데이터에 적합합니다. 외부 저장소: 매우 큰 데이터 세트의 경우 데이터를 데이터베이스 또는 NoSQL에 저장합니다.

PHP에서 MySQL 쿼리 성능을 최적화하는 방법은 무엇입니까? PHP에서 MySQL 쿼리 성능을 최적화하는 방법은 무엇입니까? Jun 03, 2024 pm 08:11 PM

선형 복잡성에서 로그 복잡성까지 조회 시간을 줄이는 인덱스를 구축하여 MySQL 쿼리 성능을 최적화할 수 있습니다. SQL 삽입을 방지하고 쿼리 성능을 향상하려면 PREPAREDStatements를 사용하세요. 쿼리 결과를 제한하고 서버에서 처리되는 데이터의 양을 줄입니다. 적절한 조인 유형 사용, 인덱스 생성, 하위 쿼리 사용 고려 등 조인 쿼리를 최적화합니다. 쿼리를 분석하여 병목 현상을 식별하고, 캐싱을 사용하여 데이터베이스 로드를 줄이고, 오버헤드를 최소화합니다.

PHP에서 MySQL 백업 및 복원을 사용하는 방법은 무엇입니까? PHP에서 MySQL 백업 및 복원을 사용하는 방법은 무엇입니까? Jun 03, 2024 pm 12:19 PM

PHP에서 MySQL 데이터베이스를 백업하고 복원하는 작업은 다음 단계에 따라 수행할 수 있습니다. 데이터베이스 백업: mysqldump 명령을 사용하여 데이터베이스를 SQL 파일로 덤프합니다. 데이터베이스 복원: mysql 명령을 사용하여 SQL 파일에서 데이터베이스를 복원합니다.

PHP를 사용하여 MySQL 테이블에 데이터를 삽입하는 방법은 무엇입니까? PHP를 사용하여 MySQL 테이블에 데이터를 삽입하는 방법은 무엇입니까? Jun 02, 2024 pm 02:26 PM

MySQL 테이블에 데이터를 삽입하는 방법은 무엇입니까? 데이터베이스에 연결: mysqli를 사용하여 데이터베이스에 대한 연결을 설정합니다. SQL 쿼리 준비: 삽입할 열과 값을 지정하는 INSERT 문을 작성합니다. 쿼리 실행: query() 메서드를 사용하여 삽입 쿼리를 실행하면 확인 메시지가 출력됩니다.

MySQL 8.4에서 mysql_native_password가 로드되지 않음 오류를 수정하는 방법 MySQL 8.4에서 mysql_native_password가 로드되지 않음 오류를 수정하는 방법 Dec 09, 2024 am 11:42 AM

MySQL 8.4(2024년 최신 LTS 릴리스)에 도입된 주요 변경 사항 중 하나는 &quot;MySQL 기본 비밀번호&quot; 플러그인이 더 이상 기본적으로 활성화되지 않는다는 것입니다. 또한 MySQL 9.0에서는 이 플러그인을 완전히 제거합니다. 이 변경 사항은 PHP 및 기타 앱에 영향을 미칩니다.

PHP에서 MySQL 저장 프로시저를 사용하는 방법은 무엇입니까? PHP에서 MySQL 저장 프로시저를 사용하는 방법은 무엇입니까? Jun 02, 2024 pm 02:13 PM

PHP에서 MySQL 저장 프로시저를 사용하려면: PDO 또는 MySQLi 확장을 사용하여 MySQL 데이터베이스에 연결합니다. 저장 프로시저를 호출하는 문을 준비합니다. 저장 프로시저를 실행합니다. 결과 집합을 처리합니다(저장 프로시저가 결과를 반환하는 경우). 데이터베이스 연결을 닫습니다.

PHP를 사용하여 MySQL 테이블을 만드는 방법은 무엇입니까? PHP를 사용하여 MySQL 테이블을 만드는 방법은 무엇입니까? Jun 04, 2024 pm 01:57 PM

PHP를 사용하여 MySQL 테이블을 생성하려면 다음 단계가 필요합니다. 데이터베이스에 연결합니다. 데이터베이스가 없으면 작성하십시오. 데이터베이스를 선택합니다. 테이블을 생성합니다. 쿼리를 실행합니다. 연결을 닫습니다.

오라클 데이터베이스와 mysql의 차이점 오라클 데이터베이스와 mysql의 차이점 May 10, 2024 am 01:54 AM

Oracle 데이터베이스와 MySQL은 모두 관계형 모델을 기반으로 하는 데이터베이스이지만 호환성, 확장성, 데이터 유형 및 보안 측면에서 Oracle이 우수하고, MySQL은 속도와 유연성에 중점을 두고 중소 규모 데이터 세트에 더 적합합니다. ① Oracle은 광범위한 데이터 유형을 제공하고, ② 고급 보안 기능을 제공하고, ③ 엔터프라이즈급 애플리케이션에 적합하고, ① MySQL은 NoSQL 데이터 유형을 지원하고, ② 보안 조치가 적고, ③ 중소 규모 애플리케이션에 적합합니다.

See all articles