首页 > php框架 > Swoole > 正文

Swoole中怎么用协程同时请求多个HTTP接口

裘德小鎮的故事
发布: 2025-09-25 14:49:01
原创
991人浏览过
在Swoole中并发请求HTTP接口需使用Co\run()开启协程环境,通过go()函数并发发起多个Swoole\Coroutine\Http\Client请求,并利用Channel收集结果以实现同步,确保非阻塞高效执行。

swoole中怎么用协程同时请求多个http接口

在Swoole中使用协程并发请求多个HTTP接口,核心是利用Swoole\Coroutine\Http\Client配合go()函数或直接协程调度实现并行。由于协程是非阻塞的,多个HTTP请求可以同时发起,而不需要等待前一个完成。

启用协程环境

确保你的Swoole已启用协程支持,通常在启动脚本中使用Co\run()或开启协程模式:

注意:Swoole 4.4+ 推荐使用 Co\run() 来包裹协程代码。
<?php
use Swoole\Coroutine as Co;

Co\run(function () {
    // 协程并发请求写在这里
});
登录后复制

并发请求多个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来等待所有请求完成,并按需获取结果。

多面鹅
多面鹅

面向求职者的AI面试平台

多面鹅25
查看详情 多面鹅
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";
});
登录后复制

关键点总结:

  • 使用Co\run()开启协程环境
  • 每个请求放在go()中并发执行
  • Channel同步结果,避免竞态和遗漏
  • 记得关闭HttpClient连接
  • 支持HTTPS需正确设置$ssl参数和端口

基本上就这些,不复杂但容易忽略细节比如端口、SSL、超时设置。

以上就是Swoole中怎么用协程同时请求多个HTTP接口的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号