首页 / PHP / phpcurl批处理-可控并发异步
phpcurl批处理-可控并发异步
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了phpcurl批处理-可控并发异步,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2252字,纯文字阅读大概需要4分钟。
内容图文
![phpcurl批处理-可控并发异步](/upload/InfoBanner/zyjiaocheng/217/2755602b263944bbba54aa76c973c0bf.jpg)
在php的手册里面有一段代码:
$mrc = curl_multi_init(); //发出请求 ....... $active = null; do { $mrc = curl_multi_exec($mh, $active); } while ($mrc == CURLM_CALL_MULTI_PERFORM); while ($active && $mrc == CURLM_OK) { if (curl_multi_select($mh) != -1) { do { $mrc = curl_multi_exec($mh, $active); } while ($mrc == CURLM_CALL_MULTI_PERFORM); } } //下面是处理请求返回的结果
这段do...while是用来控制并发的,效果是将$mrc所有的请求完毕,再执行response结果
但如果我有1000个请求,那么curl批处理将并发1000个请求,显然是不合理,所以应该要控制一个并发数,并且将剩余的连接添加到请求队列里:
参考:http://www.onlineaspect.com/2009/01/26/how-to-use-curl_multi-without-blocking/
$mh = curl_multi_init(); $ch = array(); $chunck = 10; //并发控制数 $all = count($urls);//所有的请求url数组 $chunck = $all > $chunck ? $chunck : $all; $options = array( CURLOPT_HEADER=>FALSE, CURLOPT_RETURNTRANSFER=>TRUE, CURLOPT_FOLLOWLOCATION=>TRUE, CURLOPT_MAXREDIRS=>5, CURLOPT_USERAGENT=>'Mozilla/5.0 (Windows NT 6.1; rv:6.0) Gecko/20100101 Firefox/6.0' ); for($i = 0 ; $i < $chunck ; $i++){ $ch[$i] = curl_init(); curl_setopt($ch[$i],CURLOPT_URL,$urls[$i]); curl_setopt_array($ch[$i],$options); curl_multi_add_handle($mh,$ch[$i]); } do { while(($execrun = curl_multi_exec($mh, $running)) == CURLM_CALL_MULTI_PERFORM); if($execrun != CURLM_OK)break; // a request was just completed -- find out which one while($done = curl_multi_info_read($mh)) { //获取已经返回的url在urls数组里德的index $index = array_search($done['handle'],$ch); $info = curl_getinfo($done['handle']); if ($info['http_code'] == 200){ $output = curl_multi_getcontent($ch[$index]); // request successful. process output using the callback function. $save_path = $i.'.txt';//数据保存路径 file_put_contents($save_path,$output); // start a new request (it's important to do this before removing the old one) $next = $i++;// increment i $ch[$next] = curl_init(); $options[CURLOPT_URL] = $urls[$next];//将下一个请求添加到队列 curl_setopt_array($ch[$next],$options); curl_multi_add_handle($mh, $ch[$next]); // remove the curl handle that just completed curl_multi_remove_handle($mh, $done['handle']); } else { // request failed. add error handling. } } } while ($running); curl_multi_close($mh);
使用下来效果很好,没有副作用,并发数可控,应用之处多多,自己发挥想象吧
内容总结
以上是互联网集市为您收集整理的phpcurl批处理-可控并发异步全部内容,希望文章能够帮你解决phpcurl批处理-可控并发异步所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。