php超時處理應(yīng)用場合及解決方案全面總結(jié)

字號:


    【 概述 】
    在php開發(fā)中工作里非常多使用到超時處理到超時的場合,我說幾個場景:
    1. 異步獲取數(shù)據(jù)如果某個后端數(shù)據(jù)源獲取不成功則跳過,不影響整個頁面展現(xiàn)
    2. 為了保證web服務(wù)器不會因為當個頁面處理性能差而導致無法訪問其他頁面,則會對某些頁面操作設(shè)置
    3. 對于某些上傳或者不確定處理時間的場合,則需要對整個流程中所有超時設(shè)置為無限,否則任何一個環(huán)節(jié)設(shè)置不當,都會導致莫名執(zhí)行中斷
    4. 多個后端模塊(mysql、memcached、http接口),為了防止單個接口性能太差,導致整個前面獲取數(shù)據(jù)太緩慢,影響頁面打開速度,引起雪崩
    5. 。。。很多需要超時的場合
    這些地方都需要考慮超時的設(shè)定,但是php中的超時都是分門別類,各個處理方式和策略都不同,為了系統(tǒng)的描述,我總結(jié)了php中常用的超時處理的總結(jié)。
    【web服務(wù)器超時處理】
    [ apache ]
    一般在性能很高的情況下,缺省所有超時配置都是30秒,但是在上傳文件,或者網(wǎng)絡(luò)速度很慢的情況下,那么可能觸發(fā)超時操作。
    目前apachefastcgiphp-fpm模式下有三個超時設(shè)置:
    fastcgi超時設(shè)置:
    修改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服務(wù)的連接,同時記錄一條apache錯誤日志:
    代碼如下:
    [thujan2718:30:152011][error][client10.81.41.110]fastcgi:commwithserver/home/forum/apache/apache_php/cgi-bin/php-cgiaborted:idletimeout(30sec)
    [thujan2718:30:152011][error][client10.81.41.110]fastcgi:incompleteheaders(0bytes)receivedfromserver/home/forum/apache/apache_php/cgi-bin/php-cgi
    其他fastcgi配置參數(shù)說明:
    idletimeout發(fā)呆時限
    processlifetime一個進程的最長生命周期,過期之后無條件kill
    maxprocesscount最大進程個數(shù)
    defaultminclassprocesscount每個程序啟動的最小進程個數(shù)
    defaultmaxclassprocesscount每個程序啟動的最大進程個數(shù)
    ipcconnecttimeout程序響應(yīng)超時時間
    ipccommtimeout與程序通訊的最長時間,上面的錯誤有可能就是這個值設(shè)置過小造成的
    maxrequestsperprocess每個進程最多完成處理個數(shù),達成后自殺
    [ lighttpd ]
    配置:lighttpd.conf
    lighttpd配置中,關(guān)于超時的參數(shù)有如下幾個(篇幅考慮,只寫讀超時,寫超時參數(shù)同理):
    主要涉及選項:
    代碼如下:
    server.max-keep-alive-idle=5
    server.max-read-idle=60
    server.read-timeout=0
    server.max-connection-idle=360
    --------------------------------------------------
    #每次keep-alive的最大請求數(shù),默認值是16
    server.max-keep-alive-requests=100
    #keep-alive的最長等待時間,單位是秒,默認值是5
    server.max-keep-alive-idle=1200
    #lighttpd的work子進程數(shù),默認值是0,單進程運行
    server.max-worker=2
    #限制用戶在發(fā)送請求的過程中,最大的中間停頓時間(單位是秒),
    #如果用戶在發(fā)送請求的過程中(沒發(fā)完請求),中間停頓的時間太長,lighttpd會主動斷開連接
    #默認值是60(秒)
    server.max-read-idle=1200
    #限制用戶在接收應(yīng)答的過程中,最大的中間停頓時間(單位是秒),
    #如果用戶在接收應(yīng)答的過程中(沒接完),中間停頓的時間太長,lighttpd會主動斷開連接
    #默認值是360(秒)
    server.max-write-idle=12000
    #讀客戶端請求的超時限制,單位是秒,配為0表示不作限制
    #設(shè)置小于max-read-idle時,read-timeout生效
    server.read-timeout=0
    #寫應(yīng)答頁面給客戶端的超時限制,單位是秒,配為0表示不作限制
    #設(shè)置小于max-write-idle時,write-timeout生效
    server.write-timeout=0
    #請求的處理時間上限,如果用了mod_proxy_core,那就是和后端的交互時間限制,單位是秒
    server.max-connection-idle=1200
    --------------------------------------------------
    說明:
    對于一個keep-alive連接上的連續(xù)請求,發(fā)送第一個請求內(nèi)容的最大間隔由參數(shù)max-read-idle決定,從第二個請求起,發(fā)送請求內(nèi)容的最大間隔由參數(shù)max-keep-alive-idle決定。請求間的間隔超時也由max-keep-alive-idle決定。發(fā)送請求內(nèi)容的總時間超時由參數(shù)read-timeout決定。lighttpd與后端交互數(shù)據(jù)的超時由max-connection-idle決定。
    延伸閱讀:
    [ 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 的超時設(shè)置倒是非常清晰容易理解,上面超時針對不同工作模式,但是因為超時帶來的問題是非常多的。
    延伸閱讀:
    【php本身超時處理】
    [ php-fpm ]
    配置:php-fpm.conf
    代碼如下:
    < ?xmlversion=1.0?>
    < configuration>
    //...
    setsthelimitonthenumberofsimultaneousrequeststhatwillbeserved.
    equivalenttoapachemaxclientsdirective.
    equivalenttophp_fcgi_childrenenvironmentinoriginalphp.fcgi
    usedwithanypm_style.
    #php-cgi的進程數(shù)量
    代碼如下:
    <valuename=max_children>128</value>
    thetimeout(inseconds)forservingasinglerequestafterwhichtheworkerprocesswillbeterminated
    shouldbeusedwhen'max_execution_time'inioptiondoesnotstopscriptexecutionforsomereason
    '0s'means'off'
    #php-fpm 請求執(zhí)行超時時間,0s為永不超時,否則設(shè)置一個 ns 為超時的秒數(shù)
    代碼如下:
    <valuename=request_terminate_timeout>0s</value>
    thetimeout(inseconds)forservingofsinglerequestafterwhichaphpbacktracewillbedumpedtoslow.logfile
    '0s'means'off'
    < valuename=request_slowlog_timeout>0s</value>
    < /configuration>
    說明:
    在php.ini中,有一個參數(shù)max_execution_time可以設(shè)置php腳本的最大執(zhí)行時間,但是,在php-cgi(php-fpm)中,該參數(shù)不會起效。真正能夠控制php腳本最大執(zhí)行時:
    代碼如下:
    <valuename=request_terminate_timeout>0s</value>
    就是說如果是使用mod_php5.so的模式運行max_execution_time是會生效的,但是如果是php-fpm模式中運行時不生效的。
    延伸閱讀:
    [ php ]
    配置:php.ini
    選項:
    代碼如下:
    max_execution_time=30
    或者在代碼里設(shè)置:
    代碼如下:
    ini_set(max_execution_time,30);
    set_time_limit(30);
    說明:
    對當前會話生效,比如設(shè)置0一直不超時,但是如果php的safe_mode打開了,這些設(shè)置都會不生效。
    效果一樣,但是具體內(nèi)容需要參考php-fpm部分內(nèi)容,如果php-fpm中設(shè)置了request_terminate_timeout的話,那么max_execution_time就不生效。
    【后端&接口訪問超時】
    【http訪問】
    一般我們訪問http方式很多,主要是:curl,socket,file_get_contents()等方法。
    如果碰到對方服務(wù)器一直沒有響應(yīng)的時候,我們就悲劇了,很容易把整個服務(wù)器搞死,所以在訪問http的時候也需要考慮超時的問題。
    [ curl 訪問http]
    curl 是我們常用的一種比較靠譜的訪問http協(xié)議接口的lib庫,性能高,還有一些并發(fā)支持的功能等。
    curl:
    curl_setopt($ch,opt)可以設(shè)置一些超時的設(shè)置,主要包括:
    *(重要)curlopt_timeout設(shè)置curl允許執(zhí)行的最長秒數(shù)。
    *(重要)curlopt_timeout_ms設(shè)置curl允許執(zhí)行的最長毫秒數(shù)。(在curl7.16.2中被加入。從php5.2.3起可使用。)
    curlopt_connecttimeout在發(fā)起連接前等待的時間,如果設(shè)置為0,則無限等待。
    curlopt_connecttimeout_ms嘗試連接等待的時間,以毫秒為單位。如果設(shè)置為0,則無限等待。在curl7.16.2中被加入。從php5.2.3開始可用。
    curlopt_dns_cache_timeout設(shè)置在內(nèi)存中保存dns信息的時間,默認為120秒。
    curl普通秒級超時:
    $ch=curl_init();
    curl_setopt($ch,curlopt_url,$url);
    curl_setopt($ch,curlopt_returntransfer,1);
    curl_setopt($ch,curlopt_timeout,60);//只需要設(shè)置一個秒的數(shù)量就可以
    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);是可以支持毫秒級別超時設(shè)置的
    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);//注意,毫秒超時一定要設(shè)置這個
    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){
    echocurlerror($curl_errno):$curl_errorn;
    }else{
    echodatareceived:$datan;
    }
    }else{
    //server
    sleep(10);
    echodone.;
    }
    ?>
    其他一些技巧:
    1. 按照經(jīng)驗總結(jié)是:curl版本>=libcurl/7.21.0版本,毫秒級超時是一定生效的,切記。
    2. curl_multi的毫秒級超時也有問題。。單次訪問是支持ms級超時的,curl_multi并行調(diào)多個會不準
    [流處理方式訪問http]
    除了curl,我們還經(jīng)常自己使用fsockopen、或者是file操作函數(shù)來進行http協(xié)議的處理,所以,我們對這塊的超時處理也是必須的。
    一般連接超時可以直接設(shè)置,但是流讀取超時需要單獨處理。
    自己寫代碼處理:
    代碼如下:
    $tmcurrent=gettimeofday();
    $intusgone=($tmcurrent['sec']-$tmstart['sec'])*1000000
    +($tmcurrent['usec']-$tmstart['usec']);
    if($intusgone>$this->_intreadtimeoutus){
    returnfalse;
    }
    或者使用內(nèi)置流處理函數(shù)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);//重要,設(shè)置為非阻塞模式
    stream_set_timeout($fp,$timeout);//設(shè)置超時
    $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']){
    echoconnectiontimedout!;
    }else{
    echo$data;
    }
    }
    file_get_contents超時:
    < ?php
    $timeout=array(
    'http'=>array(
    'timeout'=>5//設(shè)置一個超時時間,單位為秒
    )
    );
    $ctx=stream_context_create($timeout);
    $text=file_get_contents();
    ?>
    fopen超時:
    代碼如下:
    < ?php
    $timeout=array(
    'http'=>array(
    'timeout'=>5//設(shè)置一個超時時間,單位為秒
    )
    );
    $ctx=stream_context_create($timeout);
    if($fp=fopen()){
    while($c=fread($fp,8192)){
    echo$c;
    }
    fclose($fp);
    }
    ?>