PHP也玩并发,巧用curl 并发减少后端访问时间
說明:本人源自3篇博文
http://blog.csdn.net/zuiaituantuan/article/details/7048782
首先,先了解下 php中的curl多線程函數(shù):
# curl_multi_add_handle
# curl_multi_close
# curl_multi_exec
# curl_multi_getcontent
# curl_multi_info_read
# curl_multi_init
# curl_multi_remove_handle
# curl_multi_select
一般來說,想到要用這些函數(shù)時(shí),目的顯然應(yīng)該是要同時(shí)請求多個(gè)url,而不是一個(gè)一個(gè)依次請求,否則不如自己循環(huán)去調(diào)curl_exec好了。
步驟總結(jié)如下:
第一步:調(diào)用curl_multi_init
第二步:循環(huán)調(diào)用curl_multi_add_handle
這一步需要注意的是,curl_multi_add_handle的第二個(gè)參數(shù)是由curl_init而來的子handle。
第三步:持續(xù)調(diào)用curl_multi_exec
第四步:根據(jù)需要循環(huán)調(diào)用curl_multi_getcontent獲取結(jié)果
第五步:調(diào)用curl_multi_remove_handle,并為每個(gè)字handle調(diào)用curl_close
第六步:調(diào)用curl_multi_close
這里有一個(gè)網(wǎng)上找的簡單例子,其作者稱為dirty的例子,(稍后我會(huì)說明為何dirty):
/*
Here's a quick and dirty example for curl-multi from PHP, tested on PHP 5.0.0RC1 CLI / FreeBSD 5.2.1
*/
$connomains = array(
"http://www.cnn.com/",
"http://www.canada.com/",
"http://www.yahoo.com/"
);
$mh = curl_multi_init();
foreach ($connomains as $i => $url) {
???? $conn[$i]=curl_init($url);
????? curl_setopt($conn[$i],CURLOPT_RETURNTRANSFER,1);
????? curl_multi_add_handle ($mh,$conn[$i]);
}
do { $n=curl_multi_exec($mh,$active); } while ($active);
foreach ($connomains as $i => $url) {
????? $res[$i]=curl_multi_getcontent($conn[$i]);
????? curl_close($conn[$i]);
}
print_r($res);
?
整個(gè)使用過程差不多就是這樣,但是,這個(gè)簡單代碼有個(gè)致命弱點(diǎn),就是在do循環(huán)的那段,在整個(gè)url請求期間是個(gè)死循環(huán),它會(huì)輕易導(dǎo)致CPU占用100%。
現(xiàn)在我們來改進(jìn)它,這里要用到一個(gè)幾乎沒有任何文檔的函數(shù)curl_multi_select了,雖然C的curl庫對select有說明,但是,php里的接口和用法確與C中有不同。
把上面do的那段改成下面這樣:
??????????????? do {
??????????????????????? $mrc = curl_multi_exec($mh,$active);
??????????????? } while ($mrc == CURLM_CALL_MULTI_PERFORM);
??????????????? while ($active and $mrc == CURLM_OK) {
??????????????????????? if (curl_multi_select($mh) != -1) {
??????????????????????????????? do {
??????????????????????????????????????? $mrc = curl_multi_exec($mh, $active);
??????????????????????????????? } while ($mrc == CURLM_CALL_MULTI_PERFORM);
??????????????????????? }
??????????????? }
因?yàn)?active要等全部url數(shù)據(jù)接受完畢才變成false,所以這里用到了curl_multi_exec的返回值判斷是否還有數(shù)據(jù),當(dāng)有數(shù)據(jù)的時(shí)候就不停調(diào)用curl_multi_exec,暫時(shí)沒有數(shù)據(jù)就進(jìn)入select階段,新數(shù)據(jù)一來就可以被喚醒繼續(xù)執(zhí)行。這里的好處就是CPU的無謂消耗沒有了。
另外:還有一些細(xì)節(jié)的地方可能有時(shí)候要遇到:
控制每一個(gè)請求的超時(shí)時(shí)間,在curl_multi_add_handle之前通過curl_setopt去做:
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
判斷是否超時(shí)了或者其他錯(cuò)誤,在curl_multi_getcontent之前用:curl_error($conn[$i]);
這里我只是簡單使用上述的dirty的例子(足夠用了,并未發(fā)現(xiàn)cpu使用100%的情況)。
對“看點(diǎn)”(kandian.com)某一接口模擬并發(fā),功能是向 memcache中讀數(shù)據(jù)并寫入數(shù)據(jù)。因?yàn)楸C荜P(guān)系,相關(guān)數(shù)據(jù)及結(jié)果就不貼出了。
模擬了3次,第一次10線程同時(shí)請求1000次,第二次,100線程同時(shí)請求1000次,第三次,1000線程同時(shí)請求100次(已經(jīng)相當(dāng)費(fèi)勁了,不敢在設(shè)置超過1000的多線程)。
看來curl多線程模擬并發(fā)還是有一定局限的。
另外還懷疑,可能會(huì)因?yàn)槎嗑€程延遲帶來結(jié)果的大誤差,對比數(shù)據(jù)發(fā)現(xiàn)。在初始化和set所用時(shí)間出入不大,差別處在get方法,因此可簡單排除這點(diǎn)~~~
?
?
?
http://log.dongsheng.org/2008/07/16/curl-multiple-handlers/
通常情況下 PHP 中的 cURL 是阻塞運(yùn)行的,就是說創(chuàng)建一個(gè) cURL 請求以后必須等它執(zhí)行成功或者超時(shí)才會(huì)執(zhí)行下一個(gè)請求,curl_multi_* 系列函數(shù)使并發(fā)訪問成功可能,PHP 文檔對這個(gè)函數(shù)的介紹不太詳細(xì),用法如下:
?
$requests = array('http://www.baidu.com', 'http://www.google.com');
$main = curl_multi_init();
$results = array();
$errors = array();
$info = array();
$count = count($requests);
for($i = 0; $i < $count; $i++)
{
$handles[$i] = curl_init($requests[$i]);
var_dump($requests[$i]);
curl_setopt($handles[$i], CURLOPT_URL, $requests[$i]);
curl_setopt($handles[$i], CURLOPT_RETURNTRANSFER, 1);
curl_multi_add_handle($main, $handles[$i]);
}
$running = 0;
do {
curl_multi_exec($main, $running);
}
while($running > 0);
for($i = 0; $i < $count; $i++)
{ $results[] = curl_multi_getcontent($handles[$i]);
$errors[] = curl_error($handles[$i]);
$info[] = curl_getinfo($handles[$i]);
curl_multi_remove_handle($main, $handles[$i]);
}
curl_multi_close($main);
var_dump($results);
var_dump($errors);
var_dump($info);
?
http://www.searchtb.com/2010/12/using-multicurl-to-improve-performance.html
前言:在我們平時(shí)的程序中難免出現(xiàn)同時(shí)訪問幾個(gè)接口的情況,平時(shí)我們用curl進(jìn)行訪問的時(shí)候,一般都是單個(gè)、順序訪問,假如有3個(gè)接口,每個(gè)接口耗時(shí)500毫秒那么我們?nèi)齻€(gè)接口就要花費(fèi)1500毫秒了,這個(gè)問題太頭疼了嚴(yán)重影響了頁面訪問速度,有沒有可能并發(fā)訪問來提高速度呢?今天就簡單的說一下,利用curl并發(fā)來提高頁面訪問速度,希望大家多指導(dǎo)。1、老的curl訪問方式以及耗時(shí)統(tǒng)計(jì)
<?php function curl_fetch($url, $timeout=3){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
$errno = curl_errno($ch);
if ($errno>0) {
$data = false;
}
curl_close($ch);
return $data;
}
function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
$url_arr=array(
"taobao"=>"http://www.taobao.com",
"sohu"=>"http://www.sohu.com",
"sina"=>"http://www.sina.com.cn",
);
$time_start = microtime_float();
$data=array();
foreach ($url_arr as $key=>$val)
{
$data[$key]=curl_fetch($val);
}
$time_end = microtime_float();
$time = $time_end - $time_start;
echo "耗時(shí):{$time}";
?>
耗時(shí):0.614秒
2、curl并發(fā)訪問方式以及耗時(shí)統(tǒng)計(jì)
<?php
function curl_multi_fetch($urlarr=array()){
$result=$res=$ch=array();
$nch = 0;
$mh = curl_multi_init();
foreach ($urlarr as $nk => $url) {
$timeout=2;
$ch[$nch] = curl_init();
curl_setopt_array($ch[$nch], array(
CURLOPT_URL => $url,
CURLOPT_HEADER => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => $timeout,
));
curl_multi_add_handle($mh, $ch[$nch]);
++$nch; }
/* wait for performing request */
do {
$mrc = curl_multi_exec($mh, $running);
} while (CURLM_CALL_MULTI_PERFORM == $mrc);
while ($running && $mrc == CURLM_OK) {
// wait for network
if (curl_multi_select($mh, 0.5) > -1) {
// pull in new data;
do {
$mrc = curl_multi_exec($mh, $running);
} while (CURLM_CALL_MULTI_PERFORM == $mrc);
}
}
if ($mrc != CURLM_OK) {
error_log("CURL Data Error");
}
/* get data */
$nch = 0;
foreach ($urlarr as $moudle=>$node) {
if (($err = curl_error($ch[$nch])) == '') {
$res[$nch]=curl_multi_getcontent($ch[$nch]); $result[$moudle]=$res[$nch]; }
else
{
error_log("curl error");
}
curl_multi_remove_handle($mh,$ch[$nch]);
curl_close($ch[$nch]);
++$nch;
}
curl_multi_close($mh);
return $result;
}
$url_arr=array(
"taobao"=>"http://www.taobao.com",
"sohu"=>"http://www.sohu.com",
"sina"=>"http://www.sina.com.cn",
);
function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
$time_start = microtime_float();
$data=curl_multi_fetch($url_arr);
$time_end = microtime_float();
$time = $time_end - $time_start;
echo "耗時(shí):{$time}";
?>
耗時(shí):0.316秒
帥氣吧整個(gè)頁面訪問后端接口的時(shí)間節(jié)省了一半
3、curl相關(guān)參數(shù)
來自:http://cn2.php.net/manual/en/ref.curl.php
curl_close — Close a cURL session
curl_copy_handle — Copy a cURL handle along with all of its preferences
curl_errno — Return the last error number
curl_error — Return a string containing the last error for the current session
curl_exec — Perform a cURL session
curl_getinfo — Get information regarding a specific transfer
curl_init — Initialize a cURL session
curl_multi_add_handle — Add a normal cURL handle to a cURL multi handle
curl_multi_close — Close a set of cURL handles
curl_multi_exec — Run the sub-connections of the current cURL handle
curl_multi_getcontent — Return the content of a cURL handle if CURLOPT_RETURNTRANSFER is set
curl_multi_info_read — Get information about the current transfers
curl_multi_init — Returns a new cURL multi handle
curl_multi_remove_handle — Remove a multi handle from a set of cURL handles
curl_multi_select — Wait for activity on any curl_multi connection
curl_setopt_array — Set multiple options for a cURL transfer
curl_setopt — Set an option for a cURL transfer
curl_version — Gets cURL version information
前端開發(fā)中的性能那點(diǎn)事(三)php的opcode緩存
前端開發(fā)中的性能那點(diǎn)事(一)巧用xdebug
總結(jié)
以上是生活随笔為你收集整理的PHP也玩并发,巧用curl 并发减少后端访问时间的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 拔罐多少钱啊?
- 下一篇: 用递归法计算斐波那契数列的第n项