PHP 原生不支援多執行緒,但可透過「非阻塞 I/O + 事件迴圈」實現高並發非同步請求。本文對比三種主流方案:原生 cURL Multi(零依賴)、Swoole 協程(高效能)、ReactPHP/Amp(純 PHP 事件驅動)。
<?php
function curlMultiGet(array $urls, int $maxConcurrent = 10, int $timeout = 10): array {
$mh = curl_multi_init();
$handles = [];
$results = [];
// 批次加入 handles
foreach ($urls as $i => $url) {
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => $timeout,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_USERAGENT => 'PHP cURL Multi',
CURLOPT_SSL_VERIFYPEER => true,
]);
curl_multi_add_handle($mh, $ch);
$handles[$i] = $ch;
}
// 事件迴圈
$running = null;
do {
curl_multi_exec($mh, $running);
// 等待活動,避免 CPU 100%
curl_multi_select($mh, 0.1);
// 讀取完成的請求
while ($info = curl_multi_info_read($mh)) {
$ch = $info['handle'];
$idx = array_search($ch, $handles, true);
if ($info['result'] === CURLE_OK) {
$results[$idx] = [
'success' => true,
'data' => curl_multi_getcontent($ch),
'code' => curl_getinfo($ch, CURLINFO_HTTP_CODE),
];
} else {
$results[$idx] = [
'success' => false,
'error' => curl_error($ch),
'errno' => $info['result'],
];
}
curl_multi_remove_handle($mh, $ch);
curl_close($ch);
}
} while ($running);
curl_multi_close($mh);
return $results;
}
// 使用
$urls = array_fill(0, 20, 'https://httpbin.org/delay/1');
$start = microtime(true);
$results = curlMultiGet($urls, 10);
echo "耗時: " . (microtime(true) - $start) . "s\n"; // 約 2 秒 (20/10 並發)
<?php
// 需安裝 swoole: pecl install swoole
// php.ini: extension=swoole
use Swoole\Coroutine;
use function Swoole\Coroutine\run;
run(function() {
$urls = array_fill(0, 100, 'https://httpbin.org/delay/1');
$chan = new Coroutine\Channel(10); // 限制並發 10
$start = microtime(true);
foreach ($urls as $url) {
Coroutine::create(function() use ($url, $chan) {
$client = new Coroutine\Http\Client('httpbin.org', 443, true);
$client->set(['timeout' => 5]);
$ret = $client->get('/delay/1');
$chan->push(['url' => $url, 'status' => $client->getStatusCode(), 'body' => $client->getBody()]);
});
}
// 收集結果
$results = [];
for ($i = 0; $i < count($urls); $i++) {
$results[] = $chan->pop();
}
echo "耗時: " . (microtime(true) - $start) . "s\n"; // 約 10 秒 (100/10 並發)
});
<?php
// composer require react/http react/promise
require_once 'vendor/autoload.php';
use React\HttpClient\Factory;
use React\EventLoop\Factory as LoopFactory;
use Clue\React\Buzz\Browser;
$loop = LoopFactory::create();
$browser = new Browser(new Factory($loop));
$urls = array_fill(0, 20, 'https://httpbin.org/delay/1');
$promises = [];
$start = microtime(true);
foreach ($urls as $url) {
$promises[] = $browser->get($url)->then(
fn($res) => ['url' => $url, 'status' => $res->getStatusCode(), 'body' => (string)$res->getBody()],
fn($err) => ['url' => $url, 'error' => $err->getMessage()]
);
}
\React\Promise\all($promises)->then(function($results) use ($start) {
echo "耗時: " . (microtime(true) - $start) . "s\n";
print_r($results);
});
$loop->run();
| 維度 | cURL Multi | Swoole 協程 | ReactPHP/Amp |
|---|---|---|---|
| 依賴 | php-curl (內建) | swoole 擴充套件 | Composer 套件 (純 PHP) |
| 程式風格 | 回調/迴圈 | 同步/協程 | Promise/async-await |
| 並發效能 | 中 (受限於 select 系統調用) | 極高 (epoll/kqueue + 協程調度) | 高 (事件驅動) |
| 記憶體佔用 | 低 | 中 (協程棧) | 中 |
| 除錯難度 | 低 | 中 (協程堆疊追蹤) | 中 |
| 適用場景 | 簡單批量 API 呼叫、CI/CD、腳本 | 高併發長連線、WebSocket、微服務網關 | 中型專案、不想裝擴充套件、現代 PHP |
| Windows 支援 | 完美 | 良好 (WSL2 最佳) | 完美 |
cURL MultiHttp::pool() (底層用 cURL Multi) 或 Laravel Octane (Swoole/RoadRunner)HttpClient 非同步支援 (基於 ReactPHP)