Architecture
The mysqlnd replication and load balancing plugin is implemented as a PHP extension. It is written in C and operates under the hood of PHP. During the startup of the PHP interpreter, in the module init phase of the PHP engine, it gets registered as a mysqlnd plugin to replace selected mysqlnd C methods.
At PHP runtime, it inspects queries sent from
mysqlnd (PHP) to the MySQL server. If a query is recognized as read-only,
it will be sent to one of the configured slave servers. Statements are
considered read-only if they either start with SELECT
,
the SQL hint /*ms=slave*/
or a slave had been chosen for
running the previous query, and the query started with the SQL hint
/*ms=last_used*/
. In all other cases, the query will
be sent to the MySQL replication master server.
For better portability, applications should use the
MYSQLND_MS_MASTER_SWITCH
,
MYSQLND_MS_SLAVE_SWITCH
, and
MYSQLND_MS_LAST_USED_SWITCH
predefined mysqlnd_ms constants,
instead of their literal values, such as /*ms=slave*/
.
The plugin handles the opening and closing of database connections to both master and slave servers. From an application point of view, there continues to be only one connection handle. However, internally, this one public connection handle represents a pool of network connections that are managed by the plugin. The plugin proxies queries to the master server, and to the slaves using multiple connections.
Database connections have a state consisting of, for example, transaction
status, transaction settings, character set settings, and temporary tables.
The plugin will try to maintain the same state among all internal
connections, whenever this can be done in an automatic and transparent way.
In cases where it is not easily possible to maintain state among all
connections, such as when using BEGIN TRANSACTION
, the
plugin leaves it to the user to handle.