php实现并发请求
PHP 实现并发请求的方法
使用 cURL 多线程(Multi-cURL)
cURL 的 multi_* 函数族允许同时发起多个 HTTP 请求。示例代码:
$urls = [
'https://api.example.com/endpoint1',
'https://api.example.com/endpoint2'
];
$mh = curl_multi_init();
$handles = [];
foreach ($urls as $url) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_multi_add_handle($mh, $ch);
$handles[] = $ch;
}
$running = null;
do {
curl_multi_exec($mh, $running);
} while ($running);
$results = [];
foreach ($handles as $ch) {
$results[] = curl_multi_getcontent($ch);
curl_multi_remove_handle($mh, $ch);
}
curl_multi_close($mh);
使用 Guzzle 异步请求
Guzzle HTTP 客户端库支持 Promise 模式的并发请求:
require 'vendor/autoload.php';
$client = new GuzzleHttp\Client();
$promises = [
'request1' => $client->getAsync('https://api.example.com/endpoint1'),
'request2' => $client->getAsync('https://api.example.com/endpoint2')
];
$results = GuzzleHttp\Promise\unwrap($promises);
$response1 = $results['request1']->getBody();
$response2 = $results['request2']->getBody();
使用 Swoole 协程
Swoole 扩展提供了协程支持,可实现高性能并发:
Swoole\Runtime::enableCoroutine();
go(function () {
$http = new Swoole\Coroutine\Http\Client('api.example.com', 443, true);
$http->get('/endpoint1');
$result1 = $http->body;
$http->close();
});
go(function () {
$http = new Swoole\Coroutine\Http\Client('api.example.com', 443, true);
$http->get('/endpoint2');
$result2 = $http->body;
$http->close();
});
使用进程控制(PCNTL)
通过 fork 进程实现并行处理:
$urls = ['url1', 'url2'];
$pids = [];
foreach ($urls as $url) {
$pid = pcntl_fork();
if ($pid == -1) {
die('Could not fork');
} elseif ($pid) {
$pids[] = $pid;
} else {
// 子进程处理
$result = file_get_contents($url);
exit();
}
}
foreach ($pids as $pid) {
pcntl_waitpid($pid, $status);
}
使用 ReactPHP 事件循环
基于事件驱动的异步编程:
$loop = React\EventLoop\Factory::create();
$client = new React\Http\Browser($loop);
$promises = [
$client->get('https://api.example.com/endpoint1'),
$client->get('https://api.example.com/endpoint2')
];
React\Promise\all($promises)->then(function (array $responses) {
$response1 = $responses[0];
$response2 = $responses[1];
});
$loop->run();
注意事项
- cURL 多线程适用于大多数 PHP 环境,但需要启用 cURL 扩展
- Guzzle 需要 Composer 安装,适合现代 PHP 项目
- Swoole 性能最高但需要安装扩展
- 进程控制方法会创建真实进程,资源消耗较大
- 异步编程模式需要理解 Promise 和事件循环概念
选择方法时应考虑:
- PHP 版本和环境限制
- 并发请求的数量级
- 对性能的特殊需求
- 项目现有技术栈







