欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

PHP中几种常见的超时处理全面总结

程序员文章站 2023-02-18 11:16:41
在php开发中工作里非常多使用到超时处理到超时的场合,我说几个场景: 1. 异步获取数据如果某个后端数据源获取不成功则跳过,不影响整个页面展现 2. 为了保证web服务器不...
在php开发中工作里非常多使用到超时处理到超时的场合,我说几个场景:

1. 异步获取数据如果某个后端数据源获取不成功则跳过,不影响整个页面展现
2. 为了保证web服务器不会因为当个页面处理性能差而导致无法访问其他页面,则会对某些页面操作设置
3. 对于某些上传或者不确定处理时间的场合,则需要对整个流程中所有超时设置为无限,否则任何一个环节设置不当,都会导致莫名执行中断
4. 多个后端模块(mysql、memcached、http接口),为了防止单个接口性能太差,导致整个前面获取数据太缓慢,影响页面打开速度,引起雪崩
5. 。。。很多需要超时的场合

这些地方都需要考虑超时的设定,但是php中的超时都是分门别类,各个处理方式和策略都不同,为了系统的描述,我总结了php中常用的超时处理的总结。

【web服务器超时处理】

[ apache ]
一般在性能很高的情况下,缺省所有超时配置都是30秒,但是在上传文件,或者网络速度很慢的情况下,那么可能触发超时操作。
目前apachefastcgiphp-fpm模式下有三个超时设置:
fastcgi超时设置:
修改httpd.conf的fastcgi连接配置,类似如下:

复制代码 代码如下:

<ifmodulemod_fastcgi.c>
fastcgiexternalserver/home/forum/apache/apache_php/cgi-bin/php-cgi-socket/home/forum/php5/etc/php-fpm.sock
scriptalias/fcgi-bin/"/home/forum/apache/apache_php/cgi-bin/"
addhandlerphp-fastcgi.php
actionphp-fastcgi/fcgi-bin/php-cgi
addtypeapplication/x-httpd-php.php
</ifmodule>


缺省配置是30s,如果需要定制自己的配置,需要修改配置,比如修改为100秒:(修改后重启apache):

复制代码 代码如下:

<ifmodulemod_fastcgi.c>
fastcgiexternalserver/home/forum/apache/apache_php/cgi-bin/php-cgi-socket/home/forum/php5/etc/php-fpm.sock-idle-timeout100
scriptalias/fcgi-bin/"/home/forum/apache/apache_php/cgi-bin/"
addhandlerphp-fastcgi.php
actionphp-fastcgi/fcgi-bin/php-cgi
addtypeapplication/x-httpd-php.php
</ifmodule>

如果超时会返回500错误,断开跟后端php服务的连接,同时记录一条apache错误日志:
[thujan2718:30:152011][error][client10.81.41.110]fastcgi:commwithserver"/home/forum/apache/apache_php/cgi-bin/php-cgi"aborted:idletimeout(30sec)
[thujan2718:30:152011][error][client10.81.41.110]fastcgi:incompleteheaders(0bytes)receivedfromserver"/home/forum/apache/apache_php/cgi-bin/php-cgi"
其他fastcgi配置参数说明:
复制代码 代码如下:

idletimeout发呆时限
processlifetime一个进程的最长生命周期,过期之后无条件kill
maxprocesscount最大进程个数
defaultminclassprocesscount每个程序启动的最小进程个数
defaultmaxclassprocesscount每个程序启动的最大进程个数
ipcconnecttimeout程序响应超时时间
ipccommtimeout与程序通讯的最长时间,上面的错误有可能就是这个值设置过小造成的
maxrequestsperprocess每个进程最多完成处理个数,达成后自杀

[ lighttpd ]
配置:lighttpd.conf
lighttpd配置中,关于超时的参数有如下几个(篇幅考虑,只写读超时,写超时参数同理):
主要涉及选项:
server.max-keep-alive-idle=5
server.max-read-idle=60
server.read-timeout=0
server.max-connection-idle=360
复制代码 代码如下:

#每次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

说明:
对于一个keep-alive连接上的连续请求,发送第一个请求内容的最大间隔由参数max-read-idle决定,从第二个请求起,发送请求内容的最大间隔由参数max-keep-alive-idle决定。请求间的间隔超时也由max-keep-alive-idle决定。发送请求内容的总时间超时由参数read-timeout决定。lighttpd与后端交互数据的超时由max-connection-idle决定。
延伸阅读:
http://www.snooda.com/read/244
[ nginx ]
配置:nginx.conf
复制代码 代码如下:

http{
#fastcgi:(针对后端的fastcgi生效,fastcgi不属于proxy模式)
fastcgi_connect_timeout5;#连接超时
fastcgi_send_timeout10; #写超时
fastcgi_read_timeout10;#读取超时
#proxy:(针对proxy/upstreams的生效)
proxy_connect_timeout15s;#连接超时
proxy_read_timeout24s;#读超时
proxy_send_timeout10s; #写超时
}

说明:
nginx 的超时设置倒是非常清晰容易理解,上面超时针对不同工作模式,但是因为超时带来的问题是非常多的。
延伸阅读:
http://hi.baidu.com/pibuchou/blog/item/a1e330dd71fb8a5995ee3753.html
http://hi.baidu.com/pibuchou/blog/item/7cbccff0a3b77dc60b46e024.html
http://hi.baidu.com/pibuchou/blog/item/10a549818f7e4c9df703a626.html
http://www.apoyl.com/?p=466
【php本身超时处理】
[ php-fpm ]
配置:php-fpm.conf
复制代码 代码如下:

<?xmlversion="1.0"?>
<configuration>
//...
setsthelimitonthenumberofsimultaneousrequeststhatwillbeserved.
equivalenttoapachemaxclientsdirective.
equivalenttophp_fcgi_childrenenvironmentinoriginalphp.fcgi
usedwithanypm_style.
#php-cgi的进程数量
<valuename="max_children">128</value>
thetimeout(inseconds)forservingasinglerequestafterwhichtheworkerprocesswillbeterminated
shouldbeusedwhen'max_execution_time'inioptiondoesnotstopscriptexecutionforsomereason
'0s'means'off'
#php-fpm 请求执行超时时间,0s为永不超时,否则设置一个 ns 为超时的秒数
<valuename="request_terminate_timeout">0s</value>
thetimeout(inseconds)forservingofsinglerequestafterwhichaphpbacktracewillbedumpedtoslow.logfile
'0s'means'off'
<valuename="request_slowlog_timeout">0s</value>
</configuration>

说明:
在php.ini中,有一个参数max_execution_time可以设置php脚本的最大执行时间,但是,在php-cgi(php-fpm)中,该参数不会起效。真正能够控制php脚本最大执行时:
<valuename="request_terminate_timeout">0s</value>
就是说如果是使用mod_php5.so的模式运行max_execution_time是会生效的,但是如果是php-fpm模式中运行时不生效的。
延伸阅读:
http://blog.s135.com/file_get_contents/
[ php ]
配置:php.ini
选项:
max_execution_time=30
或者在代码里设置:
ini_set("max_execution_time",30);
set_time_limit(30);
说明:
对当前会话生效,比如设置0一直不超时,但是如果php的safe_mode打开了,这些设置都会不生效。
效果一样,但是具体内容需要参考php-fpm部分内容,如果php-fpm中设置了request_terminate_timeout的话,那么max_execution_time就不生效。
【后端&接口访问超时】
【http访问】
一般我们访问http方式很多,主要是:curl,socket,file_get_contents()等方法。
如果碰到对方服务器一直没有响应的时候,我们就悲剧了,很容易把整个服务器搞死,所以在访问http的时候也需要考虑超时的问题。
[ curl 访问http]
curl 是我们常用的一种比较靠谱的访问http协议接口的lib库,性能高,还有一些并发支持的功能等。
curl:
curl_setopt($ch,opt)可以设置一些超时的设置,主要包括:
*(重要)curlopt_timeout设置curl允许执行的最长秒数。
*(重要)curlopt_timeout_ms设置curl允许执行的最长毫秒数。(在curl7.16.2中被加入。从php5.2.3起可使用。)
curlopt_connecttimeout在发起连接前等待的时间,如果设置为0,则无限等待。
curlopt_connecttimeout_ms尝试连接等待的时间,以毫秒为单位。如果设置为0,则无限等待。在curl7.16.2中被加入。从php5.2.3开始可用。
curlopt_dns_cache_timeout设置在内存中保存dns信息的时间,默认为120秒。
curl普通秒级超时:
$ch=curl_init();
curl_setopt($ch,curlopt_url,$url);
curl_setopt($ch,curlopt_returntransfer,1);
curl_setopt($ch,curlopt_timeout,60);//只需要设置一个秒的数量就可以
curl_setopt($ch,curlopt_httpheader,$headers);
curl_setopt($ch,curlopt_useragent,$defined_vars['http_user_agent']);
curl普通秒级超时使用:
curl_setopt($ch,curlopt_timeout,60);
curl如果需要进行毫秒超时,需要增加:
curl_easy_setopt(curl,curlopt_nosignal,1l);
或者是:
curl_setopt($ch,curlopt_nosignal,true);是可以支持毫秒级别超时设置的
curl一个毫秒级超时的例子:
复制代码 代码如下:

<?php
if(!isset($_get['foo'])){
//client
$ch=curl_init('http://example.com/');
curl_setopt($ch,curlopt_returntransfer,true);
curl_setopt($ch,curlopt_nosignal,1);//注意,毫秒超时一定要设置这个
curl_setopt($ch,curlopt_timeout_ms,200);//超时毫秒,curl7.16.2中被加入。从php5.2.3起可使用
$data=curl_exec($ch);
$curl_errno=curl_errno($ch);
$curl_error=curl_error($ch);
curl_close($ch);
if($curl_errno>0){
echo"curlerror($curl_errno):$curl_errorn";
}else{
echo"datareceived:$datan";
}
}else{
//server
sleep(10);
echo"done.";
}
?>

其他一些技巧:
1. 按照经验总结是:curl版本>=libcurl/7.21.0版本,毫秒级超时是一定生效的,切记。
2. curl_multi的毫秒级超时也有问题。。单次访问是支持ms级超时的,curl_multi并行调多个会不准
[流处理方式访问http]
除了curl,我们还经常自己使用fsockopen、或者是file操作函数来进行http协议的处理,所以,我们对这块的超时处理也是必须的。
一般连接超时可以直接设置,但是流读取超时需要单独处理。
自己写代码处理:
复制代码 代码如下:

$tmcurrent=gettimeofday();
$intusgone=($tmcurrent['sec']-$tmstart['sec'])*1000000
+($tmcurrent['usec']-$tmstart['usec']);
if($intusgone>$this->_intreadtimeoutus){
returnfalse;
}

或者使用内置流处理函数stream_set_timeout()和stream_get_meta_data()处理:
复制代码 代码如下:

<?php
//timeoutinseconds
$timeout=5;
$fp=fsockopen("example.com",80,$errno,$errstr,$timeout);
if($fp){
fwrite($fp,"get/http/1.0rn");
fwrite($fp,"host:example.comrn");
fwrite($fp,"connection:closernrn");
stream_set_blocking($fp,true);//重要,设置为非阻塞模式
stream_set_timeout($fp,$timeout);//设置超时
$info=stream_get_meta_data($fp);
while((!feof($fp))&&(!$info['timed_out'])){
$data.=fgets($fp,4096);
$info=stream_get_meta_data($fp);
ob_flush;
flush();
}
if($info['timed_out']){
echo"connectiontimedout!";
}else{
echo$data;
}
}

file_get_contents超时:
复制代码 代码如下:

<?php
$timeout=array(
'http'=>array(
'timeout'=>5//设置一个超时时间,单位为秒
)
);
$ctx=stream_context_create($timeout);
$text=file_get_contents("http://example.com/",0,$ctx);
?>

fopen超时:
复制代码 代码如下:

<?php
$timeout=array(
'http'=>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);
}
?>

【mysql】
php中的mysql客户端都没有设置超时的选项,mysqli和mysql都没有,但是libmysql是提供超时选项的,只是我们在php中隐藏了而已。
那么如何在php中使用这个操作捏,就需要我们自己定义一些mysql操作常量,主要涉及的常量有:
mysql_opt_read_timeout=11;
mysql_opt_write_timeout=12;
这两个,定义以后,可以使用options设置相应的值。
不过有个注意点,mysql内部实现:
1.超时设置单位为秒,最少配置1秒
2.但mysql底层的read会重试两次,所以实际会是3秒
重试两次+ 自身一次=3倍超时时间,那么就是说最少超时时间是3秒,不会低于这个值,对于大部分应用来说可以接受,但是对于小部分应用需要优化。
查看一个设置访问mysql超时的php实例:
复制代码 代码如下:

<?php
//自己定义读写超时常量
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("connectfailed:%s/n",mysqli_connect_error());
exit();
}
//执行查询sleep1秒不超时
printf("hostinformation:%s/n",$mysqli->host_info);
if(!($res=$mysqli->query('selectsleep(1)'))){
echo"query1error:".$mysqli->error."/n";
}else{
echo"query1:querysuccess/n";
}
//执行查询sleep9秒会超时
if(!($res=$mysqli->query('selectsleep(9)'))){
echo"query2error:".$mysqli->error."/n";
}else{
echo"query2:querysuccess/n";
}
$mysqli->close();
echo"closemysqlconnection/n";
?>

延伸阅读:
http://blog.csdn.net/heiyeshuwu/article/details/5869813
【memcached】
[php扩展]
php_memcache客户端:
连接超时:boolmemcache::connect(string$host[,int$port[,int$timeout]])
在get和set的时候,都没有明确的超时设置参数。
libmemcached客户端:在php接口没有明显的超时参数。
说明:所以说,在php中访问memcached是存在很多问题的,需要自己hack部分操作,或者是参考网上补丁。
[c&c++访问memcached]
客户端:libmemcached客户端
说明:memcache超时配置可以配置小点,比如5,10个毫秒已经够用了,超过这个时间还不如从数据库查询。
下面是一个连接和读取set数据的超时的c++示例:
复制代码 代码如下:

//创建连接超时(连接到memcached)
memcached_st*memcacheproxy::_create_handle()
{
memcached_st*mmc=null;
memcached_return_tprc;
if(_mpool!=null){//getfrompool
mmc=memcached_pool_pop(_mpool,false,&prc);
if(mmc==null){
__log_warning__("memcacheproxy","gethandlefrompoolerror[%d]",(int)prc);
}
returnmmc;
}
memcached_st*handle=memcached_create(null);
if(handle==null){
__log_warning__("memcacheproxy","create_handleerror");
returnnull;
}
//设置连接/读取超时
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_returnrc;
for(uinti=0;i<_server_count;i++){
rc=memcached_server_add(handle,_ips[i],_ports[i]);
if(memcached_success!=rc){
__log_warning__("memcacheproxy","addserver[%s:%d]failed.",_ips[i],_ports[i]);
}
}
_mpool=memcached_pool_create(handle,_min_connect,_max_connect);
if(_mpool==null){
__log_warning__("memcacheproxy","create_poolerror");
returnnull;
}
mmc=memcached_pool_pop(_mpool,false,&prc);
if(mmc==null){
__log_warning__("mymemcacheproxy","gethandlefrompoolerror[%d]",(int)prc);
}
//__log_debug__("memcacheproxy","gethandle[%p]",handle);
returnmmc;
}
//设置一个key超时(set一个数据到memcached)
boolmemcacheproxy::_add(memcached_st*handle,unsignedint*key,constchar*value,intlen,unsignedinttimeout)
{
memcached_returnrc;
chartmp[1024];
snprintf(tmp,sizeof(tmp),"%u#%u",key[0],key[1]);
//有个timeout值
rc=memcached_set(handle,tmp,strlen(tmp),(char*)value,len,timeout,0);
if(memcached_success!=rc){
returnfalse;
}
returntrue;
}

//memcache读取数据超时(没有设置)
libmemcahed源码中接口定义:
libmemcached_apichar*memcached_get(memcached_st*ptr,constchar*key,size_tkey_length,size_t*value_length,uint32_t*flags,memcached_return_t*error);
libmemcached_apimemcached_return_tmemcached_mget(memcached_st*ptr,constchar*const*keys,constsize_t*key_length,size_tnumber_of_keys);
从接口中可以看出在读取数据的时候,是没有超时设置的。
延伸阅读:
http://hi.baidu.com/chinauser/item/b30af90b23335dde73e67608
http://libmemcached.org/libmemcached.html
【如何实现超时】
程序中需要有超时这种功能,比如你单独访问一个后端socket模块,socket模块不属于我们上面描述的任何一种的时候,它的协议也是私有的,那么这个时候可能需要自己去实现一些超时处理策略,这个时候就需要一些处理代码了。
[php中超时实现]
一、初级:最简单的超时实现 (秒级超时)
思路很简单:链接一个后端,然后设置为非阻塞模式,如果没有连接上就一直循环,判断当前时间和超时时间之间的差异。
phpsocket中实现原始的超时:(每次循环都当前时间去减,性能会很差,cpu占用会较高)
复制代码 代码如下:

<?
$host="127.0.0.1";
$port="80";
$timeout=15;//timeoutinseconds
$socket=socket_create(af_inet,sock_stream,sol_tcp)
ordie("unabletocreatesocketn");
socket_set_nonblock($socket) //务必设置为阻塞模式
ordie("unabletosetnonblockonsocketn");
$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("connectiontimedout.n");
}
sleep(1);
continue;
}
die(socket_strerror($err)."n");
}
socket_set_block($this->socket)//还原阻塞模式
ordie("unabletosetblockonsocketn");
?>

二、升级:使用php自带异步io去实现(毫秒级超时)
说明:
异步io:异步io的概念和同步io相对。当一个异步过程调用发出后,调用者不能立刻得到结果。实际处理这个调用的部件在完成后,通过状态、通知和回调来通知调用者。异步io将比特分成小组进行传送,小组可以是8位的1个字符或更长。发送方可以在任何时刻发送这些比特组,而接收方从不知道它们会在什么时候到达。
多路复用:复用模型是对多个io操作进行检测,返回可操作集合,这样就可以对其进行操作了。这样就避免了阻塞io不能随时处理各个io和非阻塞占用系统资源的确定。
使用socket_select()实现超时
socket_select(...,floor($timeout),ceil($timeout*1000000));
select的特点:能够设置到微秒级别的超时!
使用socket_select()的超时代码(需要了解一些异步io编程的知识去理解)
复制代码 代码如下:

编程 调用类 编程#
<?php
$server=newserver;
$client=newclient;
for(;;){
foreach($select->can_read(0)as$socket){
if($socket==$client->socket){
//newclientsocket
$select->add(socket_accept($client->socket));
}
else{
//there'ssomethingtoreadon$socket
}
}
}
?>
编程 异步多路复用io & 超时连接处理类 编程
<?php
classselect{
var$sockets;
functionselect($sockets){
$this->sockets=array();
foreach($socketsas$socket){
$this->add($socket);
}
}
functionadd($add_socket){
array_push($this->sockets,$add_socket);
}
functionremove($remove_socket){
$sockets=array();
foreach($this->socketsas$socket){
if($remove_socket!=$socket)
$sockets[]=$socket;
}
$this->sockets=$sockets;
}
functioncan_read($timeout){
$read=$this->sockets;
socket_select($read,$write=null,$except=null,$timeout);
return$read;
}
functioncan_write($timeout){
$write=$this->sockets;
socket_select($read=null,$write,$except=null,$timeout);
return$write;
}
}
?>

[c&c++中超时实现]
一般在linuxc/c++中,可以使用:alarm()设置定时器的方式实现秒级超时,或者:select()、poll()、epoll()之类的异步复用io实现毫秒级超时。也可以使用二次封装的异步io库(libevent,libev)也能实现。
一、使用alarm中用信号实现超时 (秒级超时)
说明:linux内核connect超时通常为75秒,我们可以设置更小的时间如10秒来提前从connect中返回。这里用使用信号处理机制,调用alarm,超时后产生sigalrm信号(也可使用select实现)
用alarym秒级实现 connect设置超时代码示例:
复制代码 代码如下:

//信号处理函数
staticvoidconnect_alarm(intsigno)
{
debug_printf("signalhandler");
return;
}
//alarm超时连接实现
staticvoidconn_alarm()
{
  sigfunc*sigfunc;//现有信号处理函数
  sigfunc=signal(sigalrm,connect_alarm);//建立信号处理函数connect_alarm,(如果有)保存现有的信号处理函数
inttimeout=5;
//设置闹钟
  if(alarm(timeout)!=0){
  //...闹钟已经设置处理
  }
//进行连接操作
if(connect(m_socket,(structsockaddr*)&addr,sizeof(addr))<0){
if(errno==eintr){//如果错误号设置为eintr,说明超时中断了
debug_printf("timeout");