php中file_get_contents()導致nginx出現504

來源:互聯網
上載者:User

Nginx+PHP-CGI(php-fpm) 的Web環境
突然發現系統負載上升,top 查看後發現很多 php-cgi 進程 CPU 使用率接近100%
找其中一個 CPU 100% 的 php-cgi 進程的 PID,用strace -p 10747跟蹤,結果發現以下結果:
select(7, [6], [6], [], {15, 0}) = 1 (out [6], left {15, 0})
poll([{fd=6, events=POLLIN}], 1, 0) = 0 (Timeout)
select(7, [6], [6], [], {15, 0}) = 1 (out [6], left {15, 0})
poll([{fd=6, events=POLLIN}], 1, 0) = 0 (Timeout)
select(7, [6], [6], [], {15, 0}) = 1 (out [6], left {15, 0})
poll([{fd=6, events=POLLIN}], 1, 0) = 0 (Timeout)
select(7, [6], [6], [], {15, 0}) = 1 (out [6], left {15, 0})
poll([{fd=6, events=POLLIN}], 1, 0) = 0 (Timeout)
select(7, [6], [6], [], {15, 0}) = 1 (out [6], left {15, 0})
poll([{fd=6, events=POLLIN}], 1, 0) = 0 (Timeout)
select(7, [6], [6], [], {15, 0}) = 1 (out [6], left {15, 0})
poll([{fd=6, events=POLLIN}], 1, 0) = 0 (Timeout)
select(7, [6], [6], [], {15, 0}) = 1 (out [6], left {15, 0})
poll([{fd=6, events=POLLIN}], 1, 0) = 0 (Timeout)
select(7, [6], [6], [], {15, 0}) = 1 (out [6], left {15, 0})
poll([{fd=6, events=POLLIN}], 1, 0) = 0 (Timeout)
select(7, [6], [6], [], {15, 0}) = 1 (out [6], left {15, 0})
poll([{fd=6, events=POLLIN}], 1, 0) = 0 (Timeout)
select(7, [6], [6], [], {15, 0}) = 1 (out [6], left {15, 0})
poll([{fd=6, events=POLLIN}], 1, 0) = 0 (Timeout)

幾乎可以肯定是file_get_contents()導致的問題,
原因是:file_get_contents的目標網站如果反應過慢,file_get_contents就會一直卡在那裡不會逾時,
我們知道php.ini 裡面max_execution_time 可以設定 PHP 指令碼的最大執行時間,但是,在 php-cgi(php-fpm) 中,該參數不會起效。真正能夠控制 PHP 指令碼最大執行時間的是 php-fpm.conf 設定檔中的以下參數:

The timeout (in seconds) for serving a single request after which the worker process will be terminated 
Should be used when 'max_execution_time' ini option does not stop script execution for some reason 
'0s' means 'off' 
<value name="request_terminate_timeout">0s</value>  預設值為 0 秒,也就是說,PHP 指令碼會一直執行下去。這樣,當所有的 php-cgi 進程都卡在 file_get_contents() 函數時,這台 Nginx+PHP 的 WebServer 已經無法再處理新的 PHP 請求了,Nginx 將給使用者返回“502 Bad Gateway”。修改該參數,設定一個 PHP 指令碼最大執行時間是必要的,但是,治標不治本。例如改成 30s,如果發生 file_get_contents() 擷取網頁內容較慢的情況,這就意味著 150 個 php-cgi 進程,每秒鐘只能處理 5 個請求,WebServer 同樣很難避免“502 Bad Gateway”。

要做到徹底解決,不妨重新封裝一下file_get_contents函數:

 代碼如下 複製代碼

function _file_get_content($str) {
$ctx = stream_context_create(array(  
   'http' => array(  
       'timeout' => 10 //設定一個逾時時間,單位為秒  
       )  
   )  
);  
return file_get_contents($str, 0, $ctx);  
}

如此 用_file_get_content代替直接使用file_get_contents 問題解決。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.