在Swoole中并发请求HTTP接口需使用Co\run()开启协程环境,通过go()函数并发发起多个Swoole\Coroutine\Http\Client请求,并利用Channel收集结果以实现同步,确保非阻塞高效执行。

在Swoole中使用协程并发请求多个HTTP接口,核心是利用Swoole\Coroutine\Http\Client配合go()函数或直接协程调度实现并行。由于协程是非阻塞的,多个HTTP请求可以同时发起,而不需要等待前一个完成。
启用协程环境
确保你的Swoole已启用协程支持,通常在启动脚本中使用Co\run()或开启协程模式:
Co\run() 来包裹协程代码。并发请求多个HTTP接口
通过
go()启动多个协程,每个协程处理一个HTTP请求,然后收集结果。Co\run(function () { $urls = [ 'https://httpbin.org/get?a=1', 'https://httpbin.org/get?a=2', 'https://httpbin.org/post', ]; $results = []; $clients = []; foreach ($urls as $index => $url) { go(function () use ($url, $index, &$results) { // 解析URL $parsed = parse_url($url); $host = $parsed['host']; $port = $parsed['port'] ?? (strtolower($parsed['scheme']) == 'https' ? 443 : 80); $path = $parsed['path'] . ($parsed['query'] ? "?{$parsed['query']}" : ''); $ssl = strtolower($parsed['scheme']) === 'https'; $client = new Swoole\Coroutine\Http\Client($host, $port, $ssl); $client->set([ 'timeout' => 5, ]); // 发起请求(以GET为例,POST可设置data) if (strpos($url, '/post') !== false) { $client->post($path, ['name' => 'swoole']); } else { $client->get($path); } $results[$index] = [ 'url' => $url, 'status' => $client->statusCode, 'body' => $client->body, ]; $client->close(); }); } // 等待所有协程完成(简单方式:sleep不足以控制,应使用通道或协程组) // 更推荐使用 Channel 来同步结果 });使用Channel收集结果(推荐)
用
Swoole\Coroutine\Channel来等待所有请求完成,并按需获取结果。Co\run(function () { $urls = [ 'https://httpbin.org/get?a=1', 'https://httpbin.org/get?a=2', 'https://httpbin.org/post', ]; $channel = new Swoole\Coroutine\Channel(count($urls)); $start = microtime(true); foreach ($urls as $index => $url) { go(function () use ($url, $index, $channel) { $parsed = parse_url($url); $host = $parsed['host']; $port = $parsed['port'] ?? (strtolower($parsed['scheme']) == 'https' ? 443 : 80); $path = $parsed['path'] . ($parsed['query'] ? "?{$parsed['query']}" : ''); $ssl = strtolower($parsed['scheme']) === 'https'; $client = new Swoole\Coroutine\Http\Client($host, $port, $ssl); $client->set(['timeout' => 5]); if (strpos($url, '/post') !== false) { $client->post($path, ['tool' => 'swoole', 'type' => 'coroutine']); } else { $client->get($path); } $result = [ 'index' => $index, 'url' => $url, 'status' => $client->statusCode, 'body' => json_decode($client->body, true), // 假设返回JSON ]; $client->close(); $channel->push($result); // 将结果推入通道 }); } $results = []; for ($i = 0; $i < count($urls); $i++) { $results[] = $channel->pop(); // 依次取出结果 } $channel->close(); foreach ($results as $res) { echo "请求 {$res['url']} 返回状态: {$res['status']}\n"; } echo "全部请求完成,耗时: " . (microtime(true) - $start) . "秒\n"; });关键点总结:
基本上就这些,不复杂但容易忽略细节比如端口、SSL、超时设置。










