關於php curl支援並發請求,並毫秒控制逾時
為什麼這麼做?
目前的介面話的服務調用,為了保證效能和穩定性,我們都會對調用的第三方介面做並發,逾時控制。
代碼實現(網上找的現成的)
public static function curlMultiRequest($urls, $options = array()) { $ch= array(); $results = array(); $mh = curl_multi_init(); foreach($urls as $key => $val) { $ch[$key] = curl_init(); if ($options) { curl_setopt_array($ch[$key], $options); } curl_setopt($ch[$key], CURLOPT_URL, $val); curl_multi_add_handle($mh, $ch[$key]); } $running = null; do { curl_multi_exec($mh, $running); } while ($running > 0); // Get content and remove handles. foreach ($ch as $key => $val) { $results[$key] = curl_multi_getcontent($val); curl_multi_remove_handle($mh, $val); } curl_multi_close($mh); return $results; }
調用方式:
$urls = [ 'http://www.baidu.com', 'http://www.qq.com' ];$opts = [ CURLOPT_HEADER => false, CURLOPT_TIMEOUT_MS => 50,//執行指令碼逾時 //CURLOPT_CONNECTTIMEOUT_MS => 50,//網路選址逾時 CURLOPT_RETURNTRANSFER => true, CURLOPT_NOSIGNAL => true, //這個是設定毫秒必須設定];curlMultiRequest($urls,$opts);
注意事項
1.支援毫秒 cURL 7.16.2中被加入。從PHP 5.2.3起可使用
2.CURLOPT_TIMEOUT_MS,CURLOPT_CONNECTTIMEOUT_MS 未定義時
if (!defined('CURLOPT_CONNECTTIMEOUT_MS')) { define('CURLOPT_CONNECTTIMEOUT_MS', 156);}if (!defined('CURLOPT_TIMEOUT_MS')) { define('CURLOPT_TIMEOUT_MS', 155);}
參考資料:
- http://stackoverflow.com/questions/9062798/php-curl-timeout-is-not-working
- http://www.laruence.com/2014/01/21/2939.html