php实现http异步
使用 cURL 多线程实现异步
在 PHP 中,可以通过 cURL 的多线程功能实现 HTTP 异步请求。这种方法适用于需要同时发起多个 HTTP 请求的场景。
$urls = [
'http://example.com/api1',
'http://example.com/api2',
'http://example.com/api3'
];
$mh = curl_multi_init();
$handles = [];
foreach ($urls as $url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_multi_add_handle($mh, $ch);
$handles[] = $ch;
}
$running = null;
do {
curl_multi_exec($mh, $running);
curl_multi_select($mh);
} while ($running > 0);
foreach ($handles as $ch) {
$response = curl_multi_getcontent($ch);
// 处理响应
curl_multi_remove_handle($mh, $ch);
curl_close($ch);
}
curl_multi_close($mh);
使用 Guzzle 异步客户端
Guzzle 是一个流行的 PHP HTTP 客户端,它提供了简洁的异步请求接口。

require 'vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\Promise;
$client = new Client();
$promises = [
'example1' => $client->getAsync('http://example.com/api1'),
'example2' => $client->getAsync('http://example.com/api2'),
'example3' => $client->getAsync('http://example.com/api3')
];
$results = Promise\Utils::settle($promises)->wait();
foreach ($results as $key => $result) {
if ($result['state'] === 'fulfilled') {
$response = $result['value'];
// 处理成功响应
} else {
$reason = $result['reason'];
// 处理错误
}
}
使用 ReactPHP 实现非阻塞 HTTP 请求
ReactPHP 是一个低级别的异步编程库,适合需要更精细控制异步流程的场景。

require 'vendor/autoload.php';
$loop = React\EventLoop\Factory::create();
$client = new React\Http\Browser($loop);
$client->get('http://example.com/api')->then(
function (Psr\Http\Message\ResponseInterface $response) {
// 处理成功响应
},
function (Exception $e) {
// 处理错误
}
);
$loop->run();
使用 Swoole 协程实现高性能异步
Swoole 是一个 PHP 协程框架,提供了高性能的异步 HTTP 客户端。
Swoole\Runtime::enableCoroutine();
go(function () {
$client = new Swoole\Coroutine\Http\Client('example.com', 80);
$client->get('/api');
if ($client->statusCode === 200) {
// 处理响应
}
$client->close();
});
使用消息队列实现后台处理
对于不需要立即获取结果的场景,可以通过消息队列将 HTTP 请求任务放入后台处理。
// 生产者代码
$queue = new Redis();
$queue->connect('127.0.0.1', 6379);
$queue->lPush('http_requests', json_encode([
'url' => 'http://example.com/api',
'method' => 'GET',
'data' => []
]));
// 消费者代码(后台 worker)
while ($task = $queue->rPop('http_requests')) {
$task = json_decode($task, true);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $task['url']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
// 处理响应
}
每种方法适用于不同的场景,cURL 多线程适合简单的并行请求,Guzzle 提供了更高级的接口,ReactPHP 和 Swoole 适合需要长期运行的异步应用,消息队列适合后台任务处理。






