Featured image of post PHP 发起并发请求

PHP 发起并发请求

从 PHP 中尝试一下伪并发请求功能

PHP 一直以来都是以页面级别的生存方式直接, 上一次请求和下一次的变量无法公用 (不像常驻内存语言)


官方并发请求 demo

<?php
require __DIR__ . '/../vendor/autoload.php';

use Curl\MultiCurl;

$urls = array(
    'tag3' => 'https://httpbin.org/post',
    'tag4' => 'https://httpbin.org/get',
    'tag5' => 'https://httpbin.org/html',
);

$multi_curl = new MultiCurl();


$data = [];

$multi_curl->success(function ($instance) {
    echo 'call to ' . $instance->id . ' with "' . $instance->myTag . '" was successful.' . "\n";
});
$multi_curl->error(function ($instance) {
    echo 'call to ' . $instance->id . ' with "' . $instance->myTag . '" was unsuccessful.' . "\n";
});
$multi_curl->complete(function ($instance) use (&$data) {
    echo 'call to ' . $instance->id . ' with "' . $instance->myTag . '" completed.' . "\n";
    $data[] = $instance->tag;
});

foreach ($urls as $tag => $url) {
    $instance = $multi_curl->addGet($url);
    $instance->myTag = $tag;
}

// wait all request completed
$multi_curl->start();

// tag 的顺序并不是一定的, 取决于 http 请求哪个先返回
var_dump($data);