php中的并发请求

<?php
class cUrlData{
    function index(){
    $list =array(1,2,3,4,5);
    $urls = array(
<span style="white-space:pre">	</span>'localhost/mulity.php?act=test', 
<span style="white-space:pre">	</span>'localhost/mulity.php?act=test'
) ;	
    print_r($this->async_get_url($list)); // [0] => example1, [1] => example2
 }
 
 // 并发请求函数
function async_get_url($url_array, $wait_usec = 0)
{   
    if (!is_array($url_array))
        return false;
    $wait_usec = intval($wait_usec);
    $data    = array('id'=>12);
    $handle  = array();
    $running = 0;
    $mh = curl_multi_init(); // multi curl handler
    $i = 0;
    foreach($url_array as $url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'localhost/mulity.php?act=test&id='.$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // return don't print
	curl_setopt($ch, CURLOPT_POST, true);     // 设置 
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data); 
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // 302 redirect
        curl_setopt($ch, CURLOPT_MAXREDIRS, 7);
        curl_multi_add_handle($mh, $ch); // 把 curl resource 放进 multi curl handler 里
        $handle[$i++] = $ch;
    }
    /* 执行 */
    do {
        curl_multi_exec($mh, $running);
        if ($wait_usec > 0) /* 每个 connect 要间隔多久 */
            usleep($wait_usec); // 250000 = 0.25 sec
    } while ($running > 0);
    /* 读取资料 */
    foreach($handle as $i => $ch) {
        $content  = curl_multi_getcontent($ch);
        $data[$i] = (curl_errno($ch) == 0) ? $content : false;
    }
    /* 移除 handle*/
    foreach($handle as $ch) {
        curl_multi_remove_handle($mh, $ch);
    }
    curl_multi_close($mh);
    return $data;
}
<span style="font-family: 宋体, Arial;">public function test(){</span>
  $data = isset($_GET['id'])  ?  $_GET['id'] : 110; 
     echo $data*2;
}
}

$m = new cUrlData;
$act = isset($_GET['act']) ? trim($_GET['act']) : 'index';
if (!(method_exists('cUrlData',$act))) {
    echo "您输入的的地址不正确";
    exit();
}
else  $m->$act();
?>


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值