Rolling cURL: PHP併發最佳實踐

在實際項目或者自己編寫小工具(比如新聞聚合,商品價格監控,比價)的過程中, 通常需要從第3方網站或者API接口獲取數據, 在需要處理1個URL隊列時, 爲了提高性能, 可以採用cURL提供的curl_multi_*族函數實現簡單的併發.

  本文將探討兩種具體的實現方法, 並對不同的方法做簡單的性能對比.

  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. %). 爲了儘量貼近真實的請求而又保持實驗的簡單, 在對返回結果的處理上只是做了簡單的正則表達式匹配, 而沒有進行其他複雜的操作. 另外, 爲了確定結果處理回調對性能對比測試結果的影響, 可以使用usleep模擬現實中比較負責的數據處理邏輯(如提取, 分詞, 寫入文件或數據庫等).

  性能測試中用到的回調函數爲:

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


  數據處理回調無延遲時: Rolling Curl略優, 但性能提升效果不明顯.

------------------------------------------------------------------------------------------------
Delay: 0 micro seconds, equals to 0 milli seconds
------------------------------------------------------------------------------------------------
Counter         Classic         Rolling         Winner          Excellence      Excel. %
------------------------------------------------------------------------------------------------
1               0.1193          0.0390          Rolling         0.0803          67.31%
2               0.0556          0.0477          Rolling         0.0079          14.21%
3               0.0461          0.0588          Classic         -0.0127         -21.6%
4               0.0464          0.0385          Rolling         0.0079          17.03%
5               0.0534          0.0448          Rolling         0.0086          16.1%
6               0.0540          0.0714          Classic         -0.0174         -24.37%
7               0.0386          0.0416          Classic         -0.0030         -7.21%
8               0.0357          0.0398          Classic         -0.0041         -10.3%
9               0.0437          0.0442          Classic         -0.0005         -1.13%
10              0.0319          0.0348          Classic         -0.0029         -8.33%
11              0.0529          0.0430          Rolling         0.0099          18.71%
12              0.0503          0.0581          Classic         -0.0078         -13.43%
13              0.0344          0.0225          Rolling         0.0119          34.59%
14              0.0397          0.0643          Classic         -0.0246         -38.26%
15              0.0368          0.0489          Classic         -0.0121         -24.74%
16              0.0502          0.0394          Rolling         0.0108          21.51%
17              0.0592          0.0383          Rolling         0.0209          35.3%
18              0.0302          0.0285          Rolling         0.0017          5.63%
19              0.0248          0.0553          Classic         -0.0305         -55.15%
20              0.0137          0.0131          Rolling         0.0006          4.38%
------------------------------------------------------------------------------------------------
Average         0.0458          0.0436          Rolling         0.0022          4.8%
------------------------------------------------------------------------------------------------
Summary: Classic wins 10 times, while Rolling wins 10 times


數據處理回調延遲5毫秒: Rolling Curl完勝, 性能提升40%左右.

------------------------------------------------------------------------------------------------Delay: 5000 micro seconds, equals to 5 milli seconds------------------------------------------------------------------------------------------------Counter   Classic   Rolling   Winner   Excellence  Excel. %------------------------------------------------------------------------------------------------1    0.0658   0.0352   Rolling   0.0306   46.5%2    0.0728   0.0367   Rolling   0.0361   49.59%3    0.0732   0.0387   Rolling   0.0345   47.13%4    0.0783   0.0347   Rolling   0.0436   55.68%5    0.0658   0.0286   Rolling   0.0372   56.53%6    0.0687   0.0362   Rolling   0.0325   47.31%7    0.0787   0.0337   Rolling   0.0450   57.18%8    0.0676   0.0391   Rolling   0.0285   42.16%9    0.0668   0.0351   Rolling   0.0317   47.46%10    0.0603   0.0317   Rolling   0.0286   47.43%11    0.0714   0.0350   Rolling   0.0364   50.98%12    0.0627   0.0215   Rolling   0.0412   65.71%13    0.0617   0.0401   Rolling   0.0216   35.01%14    0.0721   0.0226   Rolling   0.0495   68.65%15    0.0701   0.0428   Rolling   0.0273   38.94%16    0.0674   0.0352   Rolling   0.0322   47.77%17    0.0452   0.0425   Rolling   0.0027   5.97%18    0.0596   0.0366   Rolling   0.0230   38.59%19    0.0679   0.0480   Rolling   0.0199   29.31%20    0.0657   0.0338   Rolling   0.0319   48.55%------------------------------------------------------------------------------------------------Average   0.0671   0.0354   Rolling   0.0317   47.24%------------------------------------------------------------------------------------------------Summary: Classic wins 0 times, while Rolling wins 20 times

通過上面的性能對比, 在處理URL隊列併發的應用場景中Rolling cURL應該是更加的選擇, 併發量非常大(1000+)時, 可以控制併發隊列的最大長度, 比如20, 每當1個URL返回並處理完畢之後立即加入1個尚未請求的URL到隊列中, 這樣寫出來的代碼會更加健壯, 不至於併發數太大而卡死或崩潰. 詳細的實現請參考: http://code.google.com/p/rolling-curl/


轉自:http://www.php100.com/html/webkaifa/PHP/PHPyingyong/2012/0619/10566.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章