PHP访问MySQL查询超时处理的方法_MySQL
bitsCN.com
目前两个客户端扩展库连接超时可以设置选项来操作,比如mysqli:
//创建对象
$mysqli = mysqli_init();
//设置超时选项
$mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5);
//连接
$mysqli->real_connect('localhost', 'my_user', 'my_password', 'world');
//如果超时或者其他连接失败打印错误信息
if (mysqli_connect_errno()) {
printf("Connect failed: %s/n", mysqli_connect_error());
exit();
}
//成功输出连接信息
printf ("Connection: %s/n.", $mysqli->host_info);
$mysqli->close();
?>
这个是连接超时,但是有些时候我们需要查询读写超时,比如说我们一个数据库压力很大,或者连接很多,那么数据库查询就很缓慢,但是我希望某些不重要的数据,比如说文章点击数这种如果查询超时了就不显示,至少能够保证主体页面正确显示,但是查遍PHP手册没有发现这个操作选项或者函数。
手册里只有这么四个选项
跟踪 mysqli 的扩展源代码发现它底层调用的是 libmysqlclient 的 mysql_options:
php-5.2.8/ext/mysqli/mysqli_api.c
并且在mysqli的PHP扩展中就只导出了几个变量:
php-5.2.8/ext/mysqli/mysqli.c
大概看了一下 libmysqlclient 的代码,发现其实它自带是有读写超时设置的:
mysql-5.1.30/sql-common/client.c
因为它自己定义了很多操作选项,只是php扩展里没有:
mysql-5.1.30/include/mysql.h
看看mysql中的读写超时是如何实现的:
mysql-5.1.30/sql-common/client.c
读写超时真正操作的地方,超时处理这里重试了两次,还是写死了:
mysql-5.1.30/sql/net_serv.cc
现在基本得出了结论:
按照上面查看代码来看,目前PHP针对MySQL查询超时以下限制:
1. 超时设置单位为秒,最少配置1秒
2. 但mysql底层的read会重试两次,所以实际会是 3 秒
重试两次 + 自身一次 = 3倍超时时间。
那么就是说最少超时时间是3秒,不会低于这个值,对于大部分应用来说可以接受,但是对于小部分应用需要优化。
现在我们来看看如果我们自己要设置超时,我们自己压入 MYSQL_OPT_READ_TIMEOUT 也是可以达到读写超时效果的,写一段代码来测试一下:
//自己定义读写超时常量
if (!defined('MYSQL_OPT_READ_TIMEOUT')) {
define('MYSQL_OPT_READ_TIMEOUT', 11);
}
if (!defined('MYSQL_OPT_WRITE_TIMEOUT')) {
define('MYSQL_OPT_WRITE_TIMEOUT', 12);
}
//设置超时
$mysqli = mysqli_init();
$mysqli->options(MYSQL_OPT_READ_TIMEOUT, 3);
$mysqli->options(MYSQL_OPT_WRITE_TIMEOUT, 1);
//连接数据库
$mysqli->real_connect("localhost", "root", "root", "test");
if (mysqli_connect_errno()) {
printf("Connect failed: %s/n", mysqli_connect_error());
exit();
}
//执行查询 sleep 1秒不超时
printf("Host information: %s/n", $mysqli->host_info);
if (!($res=$mysqli->query('select sleep(1)'))) {
echo "query1 error: ". $mysqli->error ."/n";
} else {
echo "Query1: query success/n";
}
//执行查询 sleep 9秒会超时
if (!($res=$mysqli->query('select sleep(9)'))) {
echo "query2 error: ". $mysqli->error ."/n";
} else {
echo "Query2: query success/n";
}
$mysqli->close();
echo "close mysql connection/n";
?>
查看上面代码的执行结果,验证了上面的观点,第一个查询成功了,第二个查询连接被断开了:
如果需要修改这个秒级别的超时,比如改成毫秒级别的超时,只能两个地方修改:
1. 修改客户端,比如 mysqli 的 query 代码,加入定时器,超时则返回
2. 修改 Mysql 中的vio代码,因为mysql的网络处理底层都是经过vio的操作
MySQL相关的vio代码:
poll 超时:
setsockopt 超时:
基本上到这里就基本能够解决PHP在针对MySQL读写查询操作超时的处理了,希望对你有帮助。
heiyeluren的blog

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics


![VMware Horizon Client cannot be opened [Fix]](https://img.php.cn/upload/article/000/887/227/170835607042441.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
VMware Horizon Client helps you access virtual desktops conveniently. However, sometimes the virtual desktop infrastructure may experience startup issues. This article discusses the solutions you can take when the VMware Horizon client fails to start successfully. Why won't my VMware Horizon client open? When configuring VDI, if the VMWareHorizon client is not open, an error may occur. Please confirm that your IT administrator has provided the correct URL and credentials. If everything is fine, follow the solutions mentioned in this guide to resolve the issue. Fix VMWareHorizon Client Not Opening If VMW is not opening on your Windows computer
![VMware Horizon client freezes or stalls while connecting [Fix]](https://img.php.cn/upload/article/000/887/227/170942987315391.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
When connecting to a VDI using the VMWareHorizon client, we may encounter situations where the application freezes during authentication or the connection blocks. This article will explore this issue and provide ways to resolve this situation. When the VMWareHorizon client experiences freezing or connection issues, there are a few things you can do to resolve the issue. Fix VMWareHorizon client freezes or gets stuck while connecting If VMWareHorizon client freezes or fails to connect on Windows 11/10, do the below mentioned solutions: Check network connection Restart Horizon client Check Horizon server status Clear client cache Fix Ho

MQTT (MessageQueuingTelemetryTransport) is a lightweight message transmission protocol commonly used for communication between IoT devices. PHP is a commonly used server-side programming language that can be used to develop MQTT clients. This article will introduce how to use PHP to develop an MQTT client and include the following content: Basic concepts of the MQTT protocol Selection and usage examples of the PHPMQTT client library: Using the PHPMQTT client to publish and

When many friends download files, they will first browse on the web page and then transfer to the client to download. But sometimes users will encounter the problem that the Baidu Netdisk webpage cannot start the client. In response to this problem, the editor has prepared a solution for you to solve the problem that the Baidu Netdisk webpage cannot start the client. Friends in need can refer to it. Solution: 1. Maybe Baidu Netdisk is not the latest version. Manually open the Baidu Netdisk client, click the settings button in the upper right corner, and then click version upgrade. If there is no update, the following prompt will appear. If there is an update, please follow the prompts to update. 2. The detection service program of Baidu Cloud Disk may be disabled. It is possible that we manually or use security software to automatically disable the detection service program of Baidu Cloud Disk. Please check it out

A mobile client refers to an application that runs on a smartphone and provides users with various functions and services in the form of a native client or a web client. Mobile clients can be divided into two forms: original clients and web clients. Native clients refer to applications written for specific operating systems using specific programming languages and development tools. The advantage of web clients is that they have good cross-platform compatibility. , can run on different devices without operating system restrictions, but compared to the native client, the performance and user experience of the web client may be reduced.

How to write an FTP client in PHP 1. Introduction FTP (File Transfer Protocol) is a protocol used for file transfer on the network. In web development, we often need to upload or download files through FTP. As a popular server-side language, PHP provides powerful FTP functions, allowing us to easily write FTP clients. This article will introduce how to write a simple FTP client using PHP and provide code examples. 2. Connect to the FTP server in PHP, we can use f

Some Win11 users have noticed that the shield logo appears next to some software icons on their personal computers. This protects computer systems and even the important information and data stored in them from infringement. If you don't like it, you can solve it by the following method. How to remove the shield logo on the win11 client 1. Right-click the taskbar on the computer and select "Task Manager" 2. Then click "Start" above 3. Find "Windows Defender" here and right-click and select "Disable", then Just restart the computer.

If neither the client nor the server implements SSL encryption technology, it is very easy for information to be stolen by intermediary attackers during the transmission process, thus causing serious risks to data security. For this reason, corresponding measures should be taken urgently to effectively ensure the security of sensitive data. You can refer to the following methods to operate. The win11 client and server do not support the commonly used SSL1. When upgrading and transforming the server system, you can give priority to upgrading and optimizing the server system, or supplementing the required necessary components to ensure that it can smoothly support the latest SSL protocol. 2. Deploy SSL certificates. You can purchase and deploy SSL certificates issued by prestigious certification centers, and install them in the server to achieve this function. 3. Enable SSL protocol
