Simple MySQL Master HA with mysqlnd_ms_MySQL
I had the pleasure of presenting to the PHP Users Group Philippines a few days ago aboutmysqlnd_ms. The mysqlnd plugin, MySQL Master Slave, is a transparent layer on top of mysqlnd extension. This allows you to do read-write splitting and slave reads load balancing without needing to change anything from your application. But do you know you can also achieve a form of high availability with this plugin? I shared 2 forms on my presentation, using async MySQL replication either in master-slave configuration or master-master configuration, while the second form is having an all primary cluster where you can write to all nodes.
This first part is to demonstrate how you can achieve a simple HA solution using the first form. First, all the sample code here can be found on myGitHub repository. So, to use the mysqlnd_ms plugin, it uses an additional external configuration file in JSON format. This configuration file, will define your master and slave nodes, failover properties and any filters (connection selection method) you want to dictate how the algorithm will provide you the connection.
Let’s start with the mysqlnd_ms configuration I used,mysqlnd_ms_ms.ini :
JavaScript{"primary": {"master": {"master_1": {"host": "127.0.0.1","port": "33001"}},"slave": {}},"standby": {"master": {"master_1": {"host": "127.0.0.1","port": "33002"}},"slave": {}}}
{ "primary":{ "master":{ "master_1":{ "host":"127.0.0.1", "port":"33001" } }, "slave":{ } }, "standby":{ "master":{ "master_1":{ "host":"127.0.0.1", "port":"33002" } }, "slave":{ } } } |
Here, I have two applications defined, one called “primary” and another called “standby”, I have not defined any slaves for simplicity. The two MySQL instances running on port 33001 and 33002 are in master-master configuration.
mysqlnd_ms.enable = 1mysqlnd_ms.disable_rw_split = 1mysqlnd_ms.force_config_usage = 1mysqlnd_ms.config_file = /home/revin/git/demo-me/phpugph201407/mysqlnd_ms_ms.ini
mysqlnd_ms.enable=1 mysqlnd_ms.disable_rw_split=1 mysqlnd_ms.force_config_usage=1 mysqlnd_ms.config_file=/home/revin/git/demo-me/phpugph201407/mysqlnd_ms_ms.ini |
This is the custom INI file I used for the tests,master-slave.ini . The first line simply enables the plugin for use. The second line, mysqlnd_ms.disable_rw_split instructs the plugin that I should only send all queries to the master because I only have masters for this test.
As for the PHP script, the full copy can be foundhere, as it is a bit lengthy I will just explain the logic on what it does.
- To start the test, it bootstraps the test table via DROP and then CREATE queries.
- It then enters a for loop where it will execute an INSERT followed by a SELECT to validate the newly inserted row and additional information like the current active server id and the connection id.
- For every iteration of the loop, a new mysqli object is created to simulate non-persistent connections to the database server.
- To create the new connection, a call to the function connect_mysql is made which returns a mysqli object when successful. An important thing to remember here is that mysqlnd_ms uses lazy connections by default, this means that when the mysqli object is created, it is not really connected yet to the server. One has to issue a statement like 'SELECT 1' to start the connection manually or callmysqli::real_connect . Not even mysqli::ping does not work without the former, I’ve opened thisbug.
- After the mysqli object is returned, the INSERT statement will trigger mysqlnd_ms to actually establish the connection and then execute the statement. This is where the good part is, if the connection cannot be made, the query_write_mysql function will know and will re-request the connection from connect_mysql, this time within the connect_mysql function, connection to the primary will be retried at least 10 times if the type of error from the previous failure is something related to a connection like error numbers 2002 and2003 . If the connection cannot be established after 10 retries, the application creates a sentinel file as /tmp/PRIMARY_HAS_FAILED and will retry the connection to the secondary (slave or passive-master).
Here is an example run, my primary has a server id or 101 while my standby is 102:
[revin@forge phpugph201407]$ php -c master-slave.ini master-slave-ng.phpLast value 0001 from server id 101 thread id 7Last value 0003 from server id 101 thread id 837: [2002] Connection refusedConnection to host 'primary' failed: [0] Connection refused, retrying (1 of 10) in 3 secondsConnection to host 'primary' failed: [0] Connection refused, retrying (2 of 10) in 3 secondsConnection to host 'primary' failed: [0] Connection refused, retrying (3 of 10) in 3 secondsConnection to host 'primary' failed: [0] Connection refused, retrying (4 of 10) in 3 secondsConnection to host 'primary' failed: [0] Connection refused, retrying (5 of 10) in 3 secondsConnection to host 'primary' failed: [0] Connection refused, retrying (6 of 10) in 3 secondsConnection to host 'primary' failed: [0] Connection refused, retrying (7 of 10) in 3 secondsConnection to host 'primary' failed: [0] Connection refused, retrying (8 of 10) in 3 secondsConnection to host 'primary' failed: [0] Connection refused, retrying (9 of 10) in 3 secondsConnection to host 'primary' failed: [0] Connection refused, retrying (10 of 10) in 3 secondsThe primary host 'primary' has failed after 30 seconds, failing over to standby!52: [2002] Connection refusedLast value 0004 from server id 102 thread id 635Last value 0006 from server id 102 thread id 636Last value 0008 from server id 102 thread id 637[...]
[revin@forgephpugph201407]$php-cmaster-slave.inimaster-slave-ng.php Lastvalue0001fromserverid101threadid7 Lastvalue0003fromserverid101threadid8 37:[2002]Connectionrefused Connectiontohost'primary'failed:[0]Connectionrefused,retrying(1of10)in3seconds Connectiontohost'primary'failed:[0]Connectionrefused,retrying(2of10)in3seconds Connectiontohost'primary'failed:[0]Connectionrefused,retrying(3of10)in3seconds Connectiontohost'primary'failed:[0]Connectionrefused,retrying(4of10)in3seconds Connectiontohost'primary'failed:[0]Connectionrefused,retrying(5of10)in3seconds Connectiontohost'primary'failed:[0]Connectionrefused,retrying(6of10)in3seconds Connectiontohost'primary'failed:[0]Connectionrefused,retrying(7of10)in3seconds Connectiontohost'primary'failed:[0]Connectionrefused,retrying(8of10)in3seconds Connectiontohost'primary'failed:[0]Connectionrefused,retrying(9of10)in3seconds Connectiontohost'primary'failed:[0]Connectionrefused,retrying(10of10)in3seconds Theprimaryhost'primary'hasfailedafter30seconds,failingovertostandby! 52:[2002]Connectionrefused Lastvalue0004fromserverid102threadid635 Lastvalue0006fromserverid102threadid636 Lastvalue0008fromserverid102threadid637 [...] |
This is not the perfect setup and there are a number of limitations, however it tells us that if you have a simple HA requirement like if you’re not running a very critical application but still do not want to be waken up at night but rather deal with issues in the morning, this might just fit. So here are some more notes:
- If you have a master-slave configuration, you just basically shot your primary (master) in the foot during the failover. You may need to rebuild its data in the morning.
- If instead you have master-master, you might just be able to bring the primary master back online, get it caught up in replication and then delete /tmp/PRIMARY_HAS_FAILED file to switch your application back to it.
- The use of /tmp/PRIMARY_HAS_FAILED sentinel file is rudimentary, its not the only way. You should consider sending notifications to yourself when failover happens because this method requires human intervention to put back the primary master back in rotation.
The same effect can be achieved with a little more coding, but you can already take advantage of the plugin with less.
I’ve also tested the plugin on the second form where you can write to multiple masters using Percona XtraDB Cluster. I’ve found a few interesting issues there so stay tuned.

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

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

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

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

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

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

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

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

뜨거운 주제











InnoDB의 전체 텍스트 검색 기능은 매우 강력하여 데이터베이스 쿼리 효율성과 대량의 텍스트 데이터를 처리 할 수있는 능력을 크게 향상시킬 수 있습니다. 1) InnoDB는 기본 및 고급 검색 쿼리를 지원하는 역 색인화를 통해 전체 텍스트 검색을 구현합니다. 2) 매치 및 키워드를 사용하여 검색, 부울 모드 및 문구 검색을 지원합니다. 3) 최적화 방법에는 워드 세분화 기술 사용, 인덱스의 주기적 재건 및 캐시 크기 조정, 성능과 정확도를 향상시키는 것이 포함됩니다.

이 기사는 MySQL의 Alter Table 문을 사용하여 열 추가/드롭 테이블/열 변경 및 열 데이터 유형 변경을 포함하여 테이블을 수정하는 것에 대해 설명합니다.

전체 테이블 스캔은 MySQL에서 인덱스를 사용하는 것보다 빠를 수 있습니다. 특정 사례는 다음과 같습니다. 1) 데이터 볼륨은 작습니다. 2) 쿼리가 많은 양의 데이터를 반환 할 때; 3) 인덱스 열이 매우 선택적이지 않은 경우; 4) 복잡한 쿼리시. 쿼리 계획을 분석하고 인덱스 최적화, 과도한 인덱스를 피하고 정기적으로 테이블을 유지 관리하면 실제 응용 프로그램에서 최상의 선택을 할 수 있습니다.

기사는 인증서 생성 및 확인을 포함하여 MySQL에 대한 SSL/TLS 암호화 구성에 대해 설명합니다. 주요 문제는 자체 서명 인증서의 보안 영향을 사용하는 것입니다. [문자 수 : 159]

예, MySQL은 Windows 7에 설치 될 수 있으며 Microsoft는 Windows 7 지원을 중단했지만 MySQL은 여전히 호환됩니다. 그러나 설치 프로세스 중에 다음 지점이 표시되어야합니다. Windows 용 MySQL 설치 프로그램을 다운로드하십시오. MySQL의 적절한 버전 (커뮤니티 또는 기업)을 선택하십시오. 설치 프로세스 중에 적절한 설치 디렉토리 및 문자를 선택하십시오. 루트 사용자 비밀번호를 설정하고 올바르게 유지하십시오. 테스트를 위해 데이터베이스에 연결하십시오. Windows 7의 호환성 및 보안 문제에 주목하고 지원되는 운영 체제로 업그레이드하는 것이 좋습니다.

기사는 MySQL Workbench 및 Phpmyadmin과 같은 인기있는 MySQL GUI 도구에 대해 논의하여 초보자 및 고급 사용자를위한 기능과 적합성을 비교합니다. [159 자].

기사는 MySQL에서 파티셔닝, 샤딩, 인덱싱 및 쿼리 최적화를 포함하여 대규모 데이터 세트를 처리하기위한 전략에 대해 설명합니다.

클러스터 인덱스와 비 클러스터 인덱스의 차이점은 1. 클러스터 된 인덱스는 인덱스 구조에 데이터 행을 저장하며, 이는 기본 키 및 범위별로 쿼리에 적합합니다. 2. 클러스터되지 않은 인덱스는 인덱스 키 값과 포인터를 데이터 행으로 저장하며 비 예산 키 열 쿼리에 적합합니다.
