【原创】PHP超时处理全面总结
【 概述 】 在PHP开发中工作里非常多使用到超时处理到超时的场合,我说几个场景:1. 异步获取数据如果某个后端数据源获取不成功则跳过,不影响整个页面展现2. 为了保证Web服务器不会因为当个页面处理性能差而导致无法访问其他页面,则会对某些页面操作设置3.
【 概述 】 在PHP开发中工作里非常多使用到超时处理到超时的场合,我说几个场景: 1. 异步获取数据如果某个后端数据源获取不成功则跳过,不影响整个页面展现 2. 为了保证Web服务器不会因为当个页面处理性能差而导致无法访问其他页面,则会对某些页面操作设置 3. 对于某些上传或者不确定处理时间的场合,则需要对整个流程中所有超时设置为无限,否则任何一个环节设置不当,都会导致莫名执行中断 4. 多个后端模块(MySQL、Memcached、HTTP接口),为了防止单个接口性能太差,导致整个前面获取数据太缓慢,影响页面打开速度,引起雪崩 5. 。。。很多需要超时的场合 这些地方都需要考虑超时的设定,但是PHP中的超时都是分门别类,各个处理方式和策略都不同,为了系统的描述,我总结了PHP中常用的超时处理的总结。 【Web服务器超时处理】 [ Apache ] 一般在性能很高的情况下,缺省所有超时配置都是30秒,但是在上传文件,或者网络速度很慢的情况下,那么可能触发超时操作。 目前 apache fastcgi php-fpm 模式 下有三个超时设置: fastcgi 超时设置: 修改 httpd.conf 的fastcgi连接配置,类似如下:
|
IdleTimeout 发呆时限ProcessLifeTime 一个进程的最长生命周期,过期之后无条件kill MaxProcessCount 最大进程个数 DefaultMinClassProcessCount 每个程序启动的最小进程个数 DefaultMaxClassProcessCount 每个程序启动的最大进程个数 IPCConnectTimeout 程序响应超时时间 IPCCommTimeout 与程序通讯的最长时间,上面的错误有可能就是这个值设置过小造成的 MaxRequestsPerProcess 每个进程最多完成处理个数,达成后自杀 |
-------------------------------------------------- # 每次keep-alive 的最大请求数, 默认值是16 server.max-keep-alive-requests = 100 # keep-alive的最长等待时间, 单位是秒,默认值是5 server.max-keep-alive-idle = 1200 # lighttpd的work子进程数,默认值是0,单进程运行 server.max-worker = 2 # 限制用户在发送请求的过程中,最大的中间停顿时间(单位是秒), # 如果用户在发送请求的过程中(没发完请求),中间停顿的时间太长,lighttpd会主动断开连接 # 默认值是60(秒) server.max-read-idle = 1200 # 限制用户在接收应答的过程中,最大的中间停顿时间(单位是秒), # 如果用户在接收应答的过程中(没接完),中间停顿的时间太长,lighttpd会主动断开连接 # 默认值是360(秒) server.max-write-idle = 12000 # 读客户端请求的超时限制,单位是秒, 配为0表示不作限制 # 设置小于max-read-idle时,read-timeout生效 server.read-timeout = 0 # 写应答页面给客户端的超时限制,单位是秒,配为0表示不作限制 # 设置小于max-write-idle时,write-timeout生效 server.write-timeout = 0 # 请求的处理时间上限,如果用了mod_proxy_core,那就是和后端的交互时间限制, 单位是秒 server.max-connection-idle = 1200 -------------------------------------------------- |
http { #Fastcgi: (针对后端的fastcgi 生效, fastcgi 不属于proxy模式) fastcgi_connect_timeout 5; #连接超时 fastcgi_send_timeout 10; #写超时 fastcgi_read_timeout 10; #读取超时 #Proxy: (针对proxy/upstreams的生效) proxy_connect_timeout 15s; #连接超时 proxy_read_timeout 24s; #读超时 proxy_send_timeout 10s; #写超时 } |
|
0) { echo "cURL Error ($curl_errno): $curl_error\n"; } else { echo "Data received: $data\n"; } } else { // Server sleep(10); echo "Done."; } ?> |
array( 'timeout' => 5 //设置一个超时时间,单位为秒 ) ); $ctx = stream_context_create($timeout); $text = file_get_contents("http://example.com/", 0, $ctx); ?> |
array( 'timeout' => 5 //设置一个超时时间,单位为秒 ) ); $ctx = stream_context_create($timeout); if ($fp = fopen("http://example.com/", "r", false, $ctx)) { while( $c = fread($fp, 8192)) { echo $c; } fclose($fp); } ?> |
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"; ?> |
//创建连接超时(连接到Memcached) memcached_st* MemCacheProxy::_create_handle() { memcached_st * mmc = NULL; memcached_return_t prc; if (_mpool != NULL) { // get from pool mmc = memcached_pool_pop(_mpool, false, &prc); if (mmc == NULL) { __LOG_WARNING__("MemCacheProxy", "get handle from pool error [%d]", (int)prc); } return mmc; } memcached_st* handle = memcached_create(NULL); if (handle == NULL){ __LOG_WARNING__("MemCacheProxy", "create_handle error"); return NULL; } // 设置连接/读取超时 memcached_behavior_set(handle, MEMCACHED_BEHAVIOR_HASH, MEMCACHED_HASH_DEFAULT); memcached_behavior_set(handle, MEMCACHED_BEHAVIOR_NO_BLOCK, _noblock); //参数MEMCACHED_BEHAVIOR_NO_BLOCK为1使超时配置生效,不设置超时会不生效,关键时候会悲剧的,容易引起雪崩 memcached_behavior_set(handle, MEMCACHED_BEHAVIOR_CONNECT_TIMEOUT, _connect_timeout); //连接超时 memcached_behavior_set(handle, MEMCACHED_BEHAVIOR_RCV_TIMEOUT, _read_timeout); //读超时 memcached_behavior_set(handle, MEMCACHED_BEHAVIOR_SND_TIMEOUT, _send_timeout); //写超时 memcached_behavior_set(handle, MEMCACHED_BEHAVIOR_POLL_TIMEOUT, _poll_timeout); // 设置一致hash // memcached_behavior_set_distribution(handle, MEMCACHED_DISTRIBUTION_CONSISTENT); memcached_behavior_set(handle, MEMCACHED_BEHAVIOR_DISTRIBUTION, MEMCACHED_DISTRIBUTION_CONSISTENT); memcached_return rc; for (uint i = 0; i timeout, 0); if (MEMCACHED_SUCCESS != rc){ return false; } return true; } |
$host = "127.0.0.1"; $port = "80"; $timeout = 15; //timeout in seconds $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("Unable to create socket\n"); socket_set_nonblock($socket) //务必设置为阻塞模式 or die("Unable to set nonblock on socket\n"); $time = time(); //循环的时候每次都减去相应值 while (!@socket_connect($socket, $host, $port)) //如果没有连接上就一直死循环 { $err = socket_last_error($socket); if ($err == 115 || $err == 114) { if ((time() - $time) >= $timeout) //每次都需要去判断一下是否超时了 { socket_close($socket); die("Connection timed out.\n"); } sleep(1); continue; } die(socket_strerror($err) . "\n"); } socket_set_block($this->socket) //还原阻塞模式 or die("Unable to set block on socket\n"); ?> |
### 调用类 #### can_read(0) as $socket) { if ($socket == $client->socket) { // New Client Socket $select->add(socket_accept($client->socket)); } else { //there's something to read on $socket } } } ?> ### 异步多路复用IO & 超时连接处理类 ### sockets = array(); foreach ($sockets as $socket) { $this->add($socket); } } function add($add_socket) { array_push($this->sockets,$add_socket); } function remove($remove_socket) { $sockets = array(); foreach ($this->sockets as $socket) { if($remove_socket != $socket) $sockets[] = $socket; } $this->sockets = $sockets; } function can_read($timeout) { $read = $this->sockets; socket_select($read,$write = NULL,$except = NULL,$timeout); return $read; } function can_write($timeout) { $write = $this->sockets; socket_select($read = NULL,$write,$except = NULL,$timeout); return $write; } } ?> |
//信号处理函数static void connect_alarm(int signo) { debug_printf("SignalHandler"); return; } //alarm超时连接实现 static void conn_alarm() { Sigfunc * sigfunc ; //现有信号处理函数 sigfunc=signal(SIGALRM, connect_alarm); //建立信号处理函数connect_alarm,(如果有)保存现有的信号处理函数 int timeout = 5; //设置闹钟 if( alarm(timeout)!=0 ){ //... 闹钟已经设置处理 } //进行连接操作 if (connect(m_Socket, (struct sockaddr *)&addr, sizeof(addr)) |
static void conn_select() { // Open TCP Socket m_Socket = socket(PF_INET,SOCK_STREAM,0); if( m_Socket 5 timeouts.tv_usec = SOCKET_TIMEOUT_USEC ; // const -> 0 uint8_t optlen = sizeof(timeouts); if( setsockopt( m_Socket, SOL_SOCKET, SO_RCVTIMEO,&timeouts,(socklen_t)optlen) |
原文地址:【原创】PHP超时处理全面总结, 感谢原作者分享。

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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











JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.
