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

33次阅读

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

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

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

启用协程环境

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

注意:Swoole 4.4+ 推荐使用 Corun() 来包裹协程代码。

<?php use SwooleCoroutine as Co;  Corun(function () {     // 协程并发请求写在这里 });

并发请求多个HTTP接口

通过go()启动多个协程,每个协程处理一个HTTP请求,然后收集结果。

Corun(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 SwooleCoroutineHttpClient($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收集结果(推荐)

SwooleCoroutineChannel来等待所有请求完成,并按需获取结果。

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

多面鹅

面向求职者的AI面试平台

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

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

Corun(function () {     $urls = [         'https://httpbin.org/get?a=1',         'https://httpbin.org/get?a=2',         'https://httpbin.org/post',     ];      $channel = new SwooleCoroutineChannel(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 SwooleCoroutineHttpClient($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"; });

关键点总结:

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

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

以上就是Swoole中怎么用协程同时请求多个HTTP接口的详细内容,更多请关注swoole php js json go 端口 ssl 并发请求 swoole 接口 并发 channel http https ssl

swoole php js json go 端口 ssl 并发请求 swoole 接口 并发 channel http https ssl

text=ZqhQzanResources