PHP 并发请求 限制并发数量

$urls = [
    [
        'url' => 'http://example.com',
        'post' => ['param1' => 'value1', 'param2' => 'value2'],
    ],
    [
        'url' => 'http://example.org',
        'post' => ['param3' => 'value3', 'param4' => 'value4'],
    ],
];
$max_concurrency = 10;
$result = curl_multi($urls, $max_concurrency);

#PHP 并发请求 限制并发数量
function curl_multi($urls,$max_concurrency = 12){
    $urls_len = $http_len=0;
    $mhs = [];
    $ret = [];

    foreach ($urls as $uk => $req) {
        $mh_ch = curl_multi_init();
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $req['url']);

        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $req['post']);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);#跟随重定向
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);#返回结果
        curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);#强制使用IPV4协议解析域名
        curl_setopt($ch, CURLOPT_DNS_USE_GLOBAL_CACHE, true);#启用DNS缓存
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);#禁用后cURL将终止从服务端进行验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);#禁用后cURL将终止从服务端进行验证

        // 将句柄添加到批量处理队列中
        curl_multi_add_handle($mh_ch, $ch);
        $mhs[] =['mh_ch'=>$mh_ch,'ch'=>$ch,'uk'=>$uk];
        $http_len++;
    }

    while ($http_len > 0) {
        $jc=0;
        foreach ($mhs as $k => $v) {
            $jc++;
            if($jc > $max_concurrency)break;#最多同时执行10个线程
            $mhr = curl_multi_exec($v['mh_ch'], $active);
            if(!($mhr === CURLM_CALL_MULTI_PERFORM || $active)){#每全部执行完毕就释放内存 线程
                $ret[$v['uk']] = curl_multi_getcontent($v['ch']);#保存内容
                curl_multi_remove_handle($v['mh_ch'], $v['ch']);#释放
                curl_close($v['ch']);
                curl_multi_close($v['mh_ch']);
                unset($mhs[$k]);#释放
                $http_len--;
            }
        }
        usleep(50*1000);
    }
    return $ret;
}

你可能感兴趣的:(PHP,杂项,php)