PHP curl 並發最佳實務代碼分享_php技巧

來源:互聯網
上載者:User
本文將探討兩種具體的實現方法, 並對不同的方法做簡單的效能對比.

1. 經典cURL並發機制及其存在的問題

經典的cURL實現機制在網上很容易找到, 比如參考PHP線上手冊的如下實現方式:

複製代碼 代碼如下:

function classic_curl($urls, $delay) {
$queue = curl_multi_init();
$map = array();

foreach ($urls as $url) {
// create cURL resources
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_TIMEOUT, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_NOSIGNAL, true);

// add handle
curl_multi_add_handle($queue, $ch);
$map[$url] = $ch;
}

$active = null;

// execute the handles
do {
$mrc = curl_multi_exec($queue, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);

while ($active > 0 && $mrc == CURLM_OK) {
if (curl_multi_select($queue, 0.5) != -1) {
do {
$mrc = curl_multi_exec($queue, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
}
}

$responses = array();
foreach ($map as $url=>$ch) {
$responses[$url] = callback(curl_multi_getcontent($ch), $delay);
curl_multi_remove_handle($queue, $ch);
curl_close($ch);
}

curl_multi_close($queue);
return $responses;
}

首先將所有的URL壓入並發隊列, 然後執行並發過程, 等待所有請求接收完之後進行資料的解析等後續處理. 在實際的處理過程中, 受網路傳輸的影響, 部分URL的內容會優先於其他URL返回, 但是經典cURL並發必須等待最慢的那個URL返回之後才開始處理, 等待也就意味著CPU的空閑和浪費. 如果URL隊列很短, 這種空閑和浪費還處在可接受的範圍, 但如果隊列很長, 這種等待和浪費將變得不可接受.

2. 改進的Rolling cURL並發方式

仔細分析不難發現經典cURL並發還存在最佳化的空間, 最佳化的方式時當某個URL請求完畢之後儘可能快的去處理它, 邊處理邊等待其他的URL返回, 而不是等待那個最慢的介面返回之後才開始處理等工作, 從而避免CPU的空閑和浪費. 閑話不多說, 下面貼上具體的實現:
複製代碼 代碼如下:

function rolling_curl($urls, $delay) {
$queue = curl_multi_init();
$map = array();

foreach ($urls as $url) {
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_NOSIGNAL, true);

curl_multi_add_handle($queue, $ch);
$map[(string) $ch] = $url;
}

$responses = array();
do {
while (($code = curl_multi_exec($queue, $active)) == CURLM_CALL_MULTI_PERFORM) ;

if ($code != CURLM_OK) { break; }

// a request was just completed -- find out which one
while ($done = curl_multi_info_read($queue)) {

// get the info and content returned on the request
$info = curl_getinfo($done['handle']);
$error = curl_error($done['handle']);
$results = callback(curl_multi_getcontent($done['handle']), $delay);
$responses[$map[(string) $done['handle']]] = compact('info', 'error', 'results');

// remove the curl handle that just completed
curl_multi_remove_handle($queue, $done['handle']);
curl_close($done['handle']);
}

// Block for data in / output; error handling is done by curl_multi_exec
if ($active > 0) {
curl_multi_select($queue, 0.5);
}

} while ($active);

curl_multi_close($queue);
return $responses;
}


3. 兩種並發實現的效能對比

改進前後的效能對比實驗在LINUX主機上進行, 測試時使用的並發隊列如下:

http://item.taobao.com/item.htm?id=14392877692
http://item.taobao.com/item.htm?id=16231676302
http://item.taobao.com/item.htm?id=17037160462
http://item.taobao.com/item.htm?id=5522416710
http://item.taobao.com/item.htm?id=16551116403
http://item.taobao.com/item.htm?id=14088310973

簡要說明下實驗設計的原則和效能測試結果的格式: 為保證結果的可靠, 每組實驗重複20次, 在單次實驗中, 給定相同的介面URL集合, 分別測量Classic(指經典的並發機制)和Rolling(指改進後的並發機制)兩種並發機制的耗時(秒為單位), 耗時短者勝出(Winner), 並計算節省的時間(Excellence, 秒為單位)以及效能提升比例(Excel. %). 為了盡量貼近真實的請求而又保持實驗的簡單, 在對返回結果的處理上只是做了簡單的Regex匹配, 而沒有進行其他複雜的操作. 另外, 為了確定結果處理回調對效能對比測試結果的影響, 可以使用usleep類比現實中比較負責的資料處理邏輯(如提取, 分詞, 寫入檔案或資料庫等).

效能測試中用到的回呼函數為:
複製代碼 代碼如下:

function callback($data, $delay) {
preg_match_all('/<h3>(.+)<\/h3>/iU', $data, $matches);
usleep($delay);
return compact('data', 'matches');
}

資料處理回調無延遲時: Rolling Curl略優, 但效能提升效果不明顯.
資料處理回調延遲5毫秒: Rolling Curl完勝, 效能提升40%左右.
通過上面的效能對比, 在處理URL隊列並發的應用情境中Rolling cURL應該是更加的選擇, 並發量非常大(1000+)時, 可以控制並發隊列的最大長度, 比如20, 每當1個URL返回並處理完畢之後立即加入1個尚未請求的URL到隊列中, 這樣寫出來的代碼會更加健壯, 不至於並發數太大而卡死或崩潰. 詳細的實現請參考: http://code.google.com/p/rolling-curl/

聯繫我們

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