php – 重用cURL多处理程序的句柄
发布时间:2020-12-13 22:47:33 所属栏目:PHP教程 来源:网络整理
导读:好吧,我正在尝试重复使用我在初始过程中生成的句柄,但是在第一次运行后它只是停止工作.如果我删除(或重新创建整个处理程序)句柄并再次添加它,它工作正常.这可能是罪魁祸首? 我的代码目前看起来像这样: ?phpecho 'Handler amount: ';$threads = (int) trim(
好吧,我正在尝试重复使用我在初始过程中生成的句柄,但是在第一次运行后它只是停止工作.如果我删除(或重新创建整个处理程序)句柄并再次添加它,它工作正常.这可能是罪魁祸首?
我的代码目前看起来像这样: <?php echo 'Handler amount: '; $threads = (int) trim(fgets(STDIN)); if($threads < 1) { $threads = 1; } $s = microtime(true); $url = 'http://mywebsite.com/some-script.php'; $mh = curl_multi_init(); $ch = array(); for($i = 0; $i < $threads; $i++) { $ch[$i] = curl_init($url); curl_setopt_array($ch[$i],array( CURLOPT_USERAGENT => 'Mozilla/5.0 (X11; Linux i686; rv:21.0) Gecko/20130213 Firefox/21.0',CURLOPT_REFERER => $url,CURLOPT_RETURNTRANSFER => true,CURLOPT_NOBODY => true )); curl_multi_add_handle($mh,$ch[$i]); } while($mh) { $running = null; do { curl_multi_exec($mh,$running); } while($running > 0); $e = microtime(true); $totalTime = number_format($e - $s,2); if($totalTime >= 1) { echo floor($threads / $totalTime) . ' requests per second (total time '.$totalTime.'s)' . "r"; $s = microtime(true); } } foreach($ch as $handler) { curl_multi_remove_handle($mh,$handler); curl_close($handler); } curl_multi_close($mh); ?> 当我将CURLOPT_VERBOSE设置为true时,我看到很多“额外的东西不精细transfer.c:1037:0 0”消息,我在另一个问题上读到它们,似乎它是由一些显而易见的事情引起的: >太快了 AFAIK,这不是它,因为如果我每次都重新创建句柄,它们会以每秒约79个请求成功完成(每个约529个字节) 我重用句柄的过程: >创建多处理程序,并将指定数量的句柄添加到多处理程序 它执行一次所有句柄然后停止. 这真的让我很难过.有任何想法吗? 解决方法
我遇到了同样的问题(尽管使用了C)并且发现我需要移除卷曲简易手柄并将其重新添加回来.我的解决方案是删除curl_multi_perform循环末尾的所有句柄,并在外循环开始时将它们重新添加回来,我在其中重用现有的keep-alive连接:
for(;;) // loop using keep-alive connections { curl_multi_add_handle(...) while ( stillRunning ) // curl_multi_perform loop { ... curl_multi_perform(...) ... } curl_multi_remove_handle(...) } 也许这也适用于您的PHP场景.记住:不要curl_easy_cleanup或curl_easy_init中间的卷曲手柄. 如果您打开CURLOPT_VERBOSE,您可以在控制台中跟随,并确保您的连接确实可以重复使用.这解决了我的这个问题. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |