解释如何利用 Guzzle 流式下载远程 JSON

解读

国内面试中,考官问“Guzzle 流式下载远程 JSON”并不是想听“用 file_get_contents 一把梭”,而是考察候选人是否理解:

  1. 大文件或持续响应场景下“一次性读入内存”的致命缺陷;
  2. Guzzle 的 Stream 接口与 Drupal 现有体系的结合点;
  3. 在 Drupal 配置管理、缓存、日志、异常处理规范下如何写“可交付”的代码;
  4. 是否具备生产级思维:超时、重试、断网续传、内存占用、垃圾回收、PSR-18 规范、单元测试。

一句话:让候选人证明“我能安全、高效、可维护地把一个 2 GB 的远程 JSON 拉到本地,而内存始终低于 128 MB”。

知识点

  1. Guzzle HTTP 组件:Client、RequestOptions、sink、stream、progress、retry 中间件。
  2. PHP 流(StreamWrapper)、PsrHttpMessageStreamInterface、可读可写流分离。
  3. Drupal 服务容器:@http_client 默认已带 30 s 超时、代理、SSL 验证配置,不可硬编码 new Client()。
  4. 配置化:settings.php 或 deploy 阶段传入 headers、token、retry次数,避免代码写死。
  5. 大文件场景:while (!$stream->eof()) + fread 限定 chunk 大小(如 2 MB),边读边写临时文件,防止 php://temp 爆内存。
  6. 错误处理:GuzzleException 子类细分,Drupal 日志通道 logger.channel.http_client,可对接企业 ELK。
  7. 性能:BigPipe 不直接参与下载,但下载完后的 JSON 若用于页面片段,可接入缓存后端(Redis/Memcached)并打 tag,实现可失效。
  8. 测试:GuzzleHttpHandlerStackMock + PHPUnit 虚拟响应,不依赖外网;GitLab CI 中可测超时重试逻辑。
  9. 安全:远程 JSON 先过 JSON Schema 校验,再 json_decode,杜绝超大深度或非法字符造成 DOS。
  10. 国内网络:HTTPS 双向证书、SNI、跨境 CDN 回源慢,需开启 Guzzle 的 “expect” 关闭和 “keep-alive” 复用。

答案

下面给出一段可直接放进 custom 模块 src/Service/RemoteJsonFetcher.php 的生产级示例,兼顾 Drupal 编码规范与国内常见 200 MB+ 政务数据接口场景。

<?php
declare(strict_types = 1);

namespace Drupal\gov_data\Service;

use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Psr7\Utils;
use Psr\Http\Message\ResponseInterface;

/**
 * 流式下载远程 JSON,内存占用恒定.
 */
class RemoteJsonFetcher {

  private ClientInterface $httpClient;
  private FileSystemInterface $fileSystem;
  private \Drupal\Core\Logger\LoggerChannelInterface $logger;
  private string $tempDir;

  public function __construct(ClientInterface $http_client,
                              FileSystemInterface $file_system,
                              LoggerChannelFactoryInterface $logger_factory) {
    $this->httpClient  = $http_client;
    $this->fileSystem  = $file_system;
    $this->logger      = $logger_factory->get('gov_data');
    $this->tempDir     = $this->fileSystem->getTempDirectory();
  }

  /**
   * 下载并返回本地临时文件路径.
   *
   * @param string $url
   * @param array $options  可覆盖超时、headers、token
   *
   * @return string  本地临时文件绝对路径
   * @throws \RuntimeException
   */
  public function fetch(string $url, array $options = []): string {
    $tmp = $this->tempDir . '/' . uniqid('remote_', true) . '.json';
    $sink = Utils::tryFopen($tmp, 'w+b');

    $default = [
      'timeout'         => 300,
      'connect_timeout' => 10,
      'sink'            => $sink,
      'headers'         => [
        'Accept'         => 'application/json',
        'Accept-Encoding'=> 'gzip',
      ],
    ];
    $options = array_merge_recursive($default, $options);

    try {
      $this->httpClient->request('GET', $url, $options);
    } catch (GuzzleException $e) {
      $this->logger->error('流式下载失败: @url , 原因: @msg', [
        '@url'  => $url,
        '@msg'  => $e->getMessage(),
      ]);
      throw new \RuntimeException('远程文件下载异常', 0, $e);
    } finally {
      fclose($sink);
    }

    return $tmp;
  }

  /**
   * 边读边校验 JSON,防止一次性 json_decode 爆内存.
   *
   * @param string $file
   * @param int    $depth  最大递归深度,默认 512
   *
   * @return \Generator
   * @throws \RuntimeException
   */
  public function decodeLineByLine(string $file, int $depth = 512): \Generator {
    $fh = fopen($file, 'rb');
    if (!$fh) {
      throw new \RuntimeException('无法打开临时文件');
    }

    $buffer = '';
    while (!feof($fh)) {
      $line = fgets($fh, 4096);
      if ($line === FALSE) {
        break;
      }
      $buffer .= $line;
      $decoded = json_decode($buffer, true, $depth);
      if (json_last_error() === JSON_ERROR_NONE) {
        yield $decoded;
        $buffer = '';
      } elseif (json_last_error() !== JSON_ERROR_CTRL_CHAR) {
        // 出现不可恢复错误
        throw new \RuntimeException('JSON 解析错误: ' . json_last_error_msg());
      }
      // 其余情况继续读
    }
    fclose($fh);
  }
}

要点说明:

  1. 全程使用 sink 把数据直接写盘,php://temp 仅在 2 MB 内驻留内存,超过后自动落盘。
  2. 超时 5 分钟、连接超时 10 秒,适合国内跨省接口。
  3. 日志通道 gov_data 可在 settings.php 里单独配置日志级别,方便运维排障。
  4. decodeLineByLine 采用生成器,下游处理 1 条写 1 条数据库或队列,内存平稳。
  5. 临时文件由 Drupal 的 FileSystem 统一管理,权限 660,符合等保要求。
  6. 单元测试可 mock ClientInterface 返回 206 分段响应,验证重试与异常分支。

拓展思考

  1. 如果远程接口返回的是 JSON Lines(每行一个 JSON),可以去掉 buffer 逻辑,直接按行 yield,效率更高。
  2. 当文件超过 1 GB 且需要断点续传,可在请求头加 Range,并记录已下载字节到 Drupal 的 KeyValue 存储,实现“失败续拉”。
  3. 若接口方仅支持 WebSocket 持续推送 JSON 片段,可以把 Guzzle 的异步池 + Stream 接口换成 ReactPHP 或 Swoole 协程,Drupal 侧通过队列消费,实现“准实时”入库。
  4. 国内政务云要求“不出域”,可把拉取任务下沉到边缘节点(如阿里政务云 ECS),节点用 Drupal Queue + Drush 消费,中心站点只通过内网 API 获取聚合结果,既合规又降低带宽。
  5. 安全审计:临时文件下载完成后立即计算 SHA-256,与接口方提供的摘要比对,防止中间人篡改;比对通过后再入库,并记录 file_managed 表,方便后续文件生命周期管理与追踪。