關於php curl支援並發請求,並毫秒統制逾時

來源:互聯網
上載者:User
關於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
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.