美文网首页
php 并发请求 post

php 并发请求 post

作者: 风度翩翩的程序猿 | 来源:发表于2022-05-30 17:19 被阅读0次
 // 并发请求
    public function multiRequest($url,$array) {
        $timeout = 60;
        $res = array();
        $mh = curl_multi_init();//创建多个curl语柄
        
        foreach ($array as $ke => $val) {

            $post_data = json_encode($val['body'],JSON_UNESCAPED_SLASHES);
            $header = $val['header'];
            $conn[$ke] = curl_init($url);
            curl_setopt($conn[$ke], CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($conn[$ke], CURLOPT_ENCODING, 'gzip');
            curl_setopt($conn[$ke], CURLOPT_TIMEOUT, $timeout);//设置超时时间
            curl_setopt($conn[$ke], CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
            curl_setopt($conn[$ke], CURLOPT_MAXREDIRS, 7);//HTTp定向级别
            curl_setopt($conn[$ke], CURLOPT_HEADER, 0);//这里不要header,加块效率
            curl_setopt($conn[$ke], CURLOPT_HTTPHEADER, $header);
            curl_setopt($conn[$ke], CURLOPT_FOLLOWLOCATION, 1); // 302 redirect
            curl_setopt($conn[$ke], CURLOPT_RETURNTRANSFER, 1);

            curl_setopt($conn[$ke], CURLOPT_POST, 1);                //post提交方式
            curl_setopt($conn[$ke], CURLOPT_POSTFIELDS, $post_data);

            curl_multi_add_handle($mh, $conn[$ke]);
        }

        // 执行批处理句柄
        $active = null;
        do {
            $mrc = curl_multi_exec($mh, $active);//当无数据,active=true
        } while ($mrc == CURLM_CALL_MULTI_PERFORM);//当正在接受数据时
        while ($active && $mrc == CURLM_OK) {//当无数据时或请求暂停时,active=true
            do {
                $mrc = curl_multi_exec($mh, $active);
            } while ($mrc == CURLM_CALL_MULTI_PERFORM);
        }

        foreach ($array as $k => $url) {
            curl_error($conn[$k]);
            $res[$k] = curl_multi_getcontent($conn[$k]);//获得返回信息
            $header[$k] = curl_getinfo($conn[$k]);//返回头信息
            curl_close($conn[$k]);//关闭语柄
            // curl_multi_remove_handle($mh  , $conn[$k]);//释放资源
        }

        curl_multi_close($mh);
        foreach ($res as $key => &$value) {
            $value = json_decode($value, true);
            $res[$key]['parms_data'] = $array[$key]['body'];
            $res[$key]['user_data'] = $array[$key]['user_data'];
        }
        return $res;
    }

相关文章

网友评论

      本文标题:php 并发请求 post

      本文链接:https://www.haomeiwen.com/subject/nxnoprtx.html