【已解决】Response在Linux下分段响应不生效

xgdd1987

问题描述

我在windows开发环境下,测试没问题。但是部署到Linux服务器上后,分段响应不生效,会等全部返回后页面才展示。使用了文档上的测试代码,也是这个问题。

public function test(Request $request): Response
    {
        //获取连接
        $connection = $request->connection;
        // 定时发送http包体
        $timer = Timer::add(1, function () use ($connection, &$timer) {
            static $i = 0;
            if ($i++ < 10) {
                // 发送http包体
                $connection->send(new Chunk((string)$i));
            } else {
                // 删除不用的定时器,避免定时器越来越多内存泄漏
                Timer::del($timer);
                // 输出空的Chunk包体通知客户端响应结束
                $connection->send(new Chunk(''));
            }
        });
        // 先输出一个带Transfer-Encoding: chunked的http头,http包体异步发送
        return response()->withHeaders([
            "Transfer-Encoding" => "chunked",
        ]);
    }
63 1 0
1个回答

xgdd1987

前端不能分段接收数据跟webman无关,原因是nginx采用了Http2,http2不支持chunked。修改为流式输出就可以了。在nginx中增加配置:

proxy_buffering off;  # 禁用缓冲
proxy_cache off;     # 禁用缓存
chunked_transfer_encoding on;  # 启用分块传输

完整配置如下:

# 将请求转发到webman
  location ^~ / {
      proxy_set_header Host $http_host;
      proxy_set_header X-Forwarded-For $remote_addr;
      proxy_set_header X-Forwarded-Proto $scheme;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_http_version 1.1;
      proxy_set_header Connection "";
      proxy_buffering off;  # 禁用缓冲
      proxy_cache off;     # 禁用缓存
      chunked_transfer_encoding on;  # 启用分块传输
      if (!-f $request_filename){
          proxy_pass http://127.0.0.1:8795;
      }
  }

  # 拒绝访问所有以 .php 结尾的文件
  location ~ \.php$ {
      return 404;
  }

  # 允许访问 .well-known 目录
  location ~ ^/\.well-known/ {
    allow all;
  }

  # 拒绝访问所有以 . 开头的文件或目录
  location ~ /\. {
      return 404;
  }
  • 暂无评论
🔝