一.首先,mysqlnd是啥个玩意?
为什么要使用mysqlnd
原来的libmysql用的好好的,为什么还要搞一个mysqlnd出来呢?
二.mysqlnd插件
这个扩展, 主要实现了, 连接保持和切换, 负载均衡和读写分离等, 也就是说, 这个扩展会去分别PHP发给MySQL的query, 如果是”读”的query, 就会把query发送给从库(配置中指明), 并且支持负载均衡; 而如果是”写”的query, 就会把query发送给主库.
不过这个扩展需要搭配mysqlnd一起使用(从PHP5.4 beta1开始, 我们已经把mysqlnd作为mysql, mysqli, pdo的默认链接目标, 当然, 你也可以通过–with-mysql=***来制定你想要链接到libmysql).
这个扩展使用的方法也很简单, 首先在php.ini中定义配置:
- mysqlnd_ms.enable=1
- mysqlnd_ms.ini_file=/path/to/mysqlnd_ms_plugin.ini
之后, 在你指明的mysqlnd_ms_plugin.ini中配置好MySQL的主从库就好了:
- [myapp]
- master[]=localhost:/tmp/mysql.sock
- slave[]=192.168.2.27:3306
博文发出以后, Ulf提醒我, 从1.1.0开始, 配置文件改为JSON格式:
Ulf_Wendel: @laruence >Thx for the blog. Please note, mysqlnd_ms config format was changed in 1.1.0. Now JSON based
所以新的配置应该类似于如下格式:
- {
- "myapp": {
- "master": {
- "master_0": {
- "host": "localhost",
- "socket": "\/tmp\/mysql.sock"
- }
- },
- "slave": {
- "slave_0": {
- "host": "192.168.2.27",
- "port": "3306"
- }
- }
- }
- }
[mysqlnd_ms]
extension = mysqlnd_ms.so
mysqlnd_ms.enable = On
mysqlnd_ms.config_file = /etc/php5/conf.d/mysqlnd_ms.conf
然后在mysqlnd_ms.conf 配制
{ "myapp": { "master": { "master_0": { "host": "localhost", "socket": "\/tmp\/mysql.sock" } }, "slave": { "slave_0": { "host": "192.168.2.27", "port": "3306" } },
"server_charset" : "utf8", "master_on_write" : 1, #防止主从读取不一样的情况 "failover": {"strategy": "master" } } }
链接方式修改如下:
- <?php
- /* Load balanced following "myapp" section rules from the plugins config file */
- $mysqli = new mysqli("myapp", "username", "password", "database");
- $pdo = new PDO('mysql:host=myapp;dbname=database', 'username', 'password');
- $mysql = mysql_connect("myapp", "username", "password");
- ?>
然后就和你之前一样的来开发了.
mysqlnd_qc介绍 query cache查询缓存.
<?php
/* Use constants for maximum portability */
$query = "/*" . MYSQLND_QC_ENABLE_SWITCH . "*/SELECT id FROM test";
/* Valid but less portable: default TTL */
$query = "/*qc=on*/SELECT id FROM test";
/* Valid but less portable: per statement TTL */
$query = "/*qc=on*//*qc_ttl=5*/SELECT id FROM test";
printf("MYSQLND_QC_ENABLE_SWITCH: %s\n", MYSQLND_QC_ENABLE_SWITCH);
printf("MYSQLND_QC_DISABLE_SWITCH: %s\n", MYSQLND_QC_DISABLE_SWITCH);
printf("MYSQLND_QC_TTL_SWITCH: %s\n", MYSQLND_QC_TTL_SWITCH);