>  기사  >  백엔드 개발  >  PHP 컬 비동기 동시 요청 정보 http

PHP 컬 비동기 동시 요청 정보 http

藏色散人
藏色散人앞으로
2021-01-06 16:30:065477검색

추천: "PHP Video Tutorial"

먼저 동기화 코드와 요청 시간을 살펴보겠습니다.

$start_time=date("h:i:sa");
for ($i=0; $i <100 ; $i++) { 
	$urls[]="http://www.downxia.com/downinfo/2315".$i.".html";
	GetTitle(geturl("http://www.downxia.com/downinfo/2315".$i.".html"));
}
function geturl($url){
       
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        
        $output = curl_exec($ch);
        curl_close($ch);

        return $output;
}
function GetTitle($output){

	preg_match(&#39;/<title>.*<\/title>/i&#39;,$output,$matches);
	var_dump($matches[0]);
}
$end_time=date("h:i:sa");
echo &#39;开始时间是:&#39;.$start_time;
echo &#39;结束时间是:&#39;.$end_time;

하단을 보면 27초가 걸린 것을 볼 수 있습니다.

다음으로, PHP Curl의 비동기 동시 http 요청에 소요된 코드와 시간을 살펴보겠습니다.

$start_time=date("h:i:sa");

$urls=[];
for ($i=0; $i <100 ; $i++) { 
	$urls[]="http://www.downxia.com/downinfo/2315".$i.".html";
}
var_dump($urls);
// GetTitle(&#39;klasjdkla<title>313asds12</title>&#39;);

rolling_curl($urls,&#39;GetTitle&#39;);

function GetTitle($output){

	preg_match(&#39;/<title>.*<\/title>/i&#39;,$output,$matches);
	var_dump($matches[0]);
}
$end_time=date("h:i:sa");

echo &#39;开始时间是:&#39;.$start_time;
echo &#39;结束时间是:&#39;.$end_time;

function rolling_curl($urls, $callback, $custom_options = null)
{//多个url访问

    // make sure the rolling window isn&#39;t greater than the # of urls
    $rolling_window = 5;
    $rolling_window = (sizeof($urls) < $rolling_window) ? sizeof($urls) : $rolling_window;

    $master   = curl_multi_init();
    $curl_arr = array();

    // add additional curl options here
    $std_options = array(
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS      => 5
        );
    $options = ($custom_options) ? ($std_options + $custom_options) : $std_options;

    // start the first batch of requests
    for ($i = 0; $i < $rolling_window; $i++) {
        $ch                   = curl_init();
        $options[CURLOPT_URL] = $urls[$i];
        curl_setopt_array($ch, $options);
        curl_multi_add_handle($master, $ch);
    }

    do {
        while (($execrun = curl_multi_exec($master, $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($master)) {
            $info = curl_getinfo($done[&#39;handle&#39;]);
            if ($info[&#39;http_code&#39;] == 200) {
                $output = curl_multi_getcontent($done[&#39;handle&#39;]);

                // request successful.  process output using the callback function.
                $callback($output);

                // start a new request (it&#39;s important to do this before removing the old one)
                $ch                   = curl_init();
                $options[CURLOPT_URL] = $urls[$i++]; // increment i
                curl_setopt_array($ch, $options);
                curl_multi_add_handle($master, $ch);

                // remove the curl handle that just completed
                curl_multi_remove_handle($master, $done[&#39;handle&#39;]);
            } else {
                // request failed.  add error handling.
            }
        }
    } while ($running);

    curl_multi_close($master);
    return true;
}

3초밖에 안 걸렸나요? 사실 동기화에 비해 시작이 느리고 처음에는 2초 정도 멈췄기 때문에 5초 정도 걸린 것 같아요.

http 요청 효율성, 비동기가 동기보다 훨씬 높다는 것은 의심의 여지가 없습니다.

핵심 요청 코드는 다음과 같습니다. (외국인이 작성한 글이라 약간의 문제가 있습니다. 마지막 프롬프트는 정의되지 않은 오프셋입니다.)

function rolling_curl($urls, $callback, $custom_options = null)
{//多个url访问

    // make sure the rolling window isn&#39;t greater than the # of urls
    $rolling_window = 5;
    $rolling_window = (sizeof($urls) < $rolling_window) ? sizeof($urls) : $rolling_window;

    $master   = curl_multi_init();
    $curl_arr = array();

    // add additional curl options here
    $std_options = array(
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS      => 5
        );
    $options = ($custom_options) ? ($std_options + $custom_options) : $std_options;

    // start the first batch of requests
    for ($i = 0; $i < $rolling_window; $i++) {
        $ch                   = curl_init();
        $options[CURLOPT_URL] = $urls[$i];
        curl_setopt_array($ch, $options);
        curl_multi_add_handle($master, $ch);
    }

    do {
        while (($execrun = curl_multi_exec($master, $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($master)) {
            $info = curl_getinfo($done[&#39;handle&#39;]);
            if ($info[&#39;http_code&#39;] == 200) {
                $output = curl_multi_getcontent($done[&#39;handle&#39;]);

                // request successful.  process output using the callback function.
                $callback($output);

                // start a new request (it&#39;s important to do this before removing the old one)
                $ch                   = curl_init();
                $options[CURLOPT_URL] = $urls[$i++]; // increment i
                curl_setopt_array($ch, $options);
                curl_multi_add_handle($master, $ch);

                // remove the curl handle that just completed
                curl_multi_remove_handle($master, $done[&#39;handle&#39;]);
            } else {
                // request failed.  add error handling.
            }
        }
    } while ($running);

    curl_multi_close($master);
    return true;
}

수정하세요. 새 URL을 추가할 때 판단을 추가하세요. // $i가 $urls 배열의 크기와 같으면 늘릴 필요가 없습니다.

function rolling_curl($urls, $callback, $custom_options = null)
{//多个url访问

    // make sure the rolling window isn&#39;t greater than the # of urls
    $rolling_window = 5;
    $rolling_window = (sizeof($urls) < $rolling_window) ? sizeof($urls) : $rolling_window;

    $master   = curl_multi_init();
    $curl_arr = array();

    // add additional curl options here
    $std_options = array(
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS      => 5
        );
    $options = ($custom_options) ? ($std_options + $custom_options) : $std_options;

    // start the first batch of requests
    for ($i = 0; $i < $rolling_window; $i++) {
        $ch                   = curl_init();
        $options[CURLOPT_URL] = $urls[$i];
        curl_setopt_array($ch, $options);
        curl_multi_add_handle($master, $ch);
    }

    do {
        while (($execrun = curl_multi_exec($master, $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($master)) {
            $info = curl_getinfo($done[&#39;handle&#39;]);
            if ($info[&#39;http_code&#39;] == 200) {
                $output = curl_multi_getcontent($done[&#39;handle&#39;]);

                // request successful.  process output using the callback function.
                $callback($output);

                // start a new request (it&#39;s important to do this before removing the old one)
                // 当$i等于$urls数组大小时不用再增加了
                if($i<sizeof($urls)){
                    $ch                   = curl_init();
                    $options[CURLOPT_URL] = $urls[$i++]; // increment i
                    curl_setopt_array($ch, $options);
                    curl_multi_add_handle($master, $ch);
                }
                // remove the curl handle that just completed
                curl_multi_remove_handle($master, $done[&#39;handle&#39;]);
            } else {
                // request failed.  add error handling.
            }
        }
    } while ($running);

    curl_multi_close($master);
    return true;
}

그렇습니다. 끝났습니다. 잊지 않도록 적어 두세요.

위 내용은 PHP 컬 비동기 동시 요청 정보 http의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 csdn.net에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제