为什么这段代码会对我的服务器性能产生如此负面的影响?

Why does this code so negatively affect my server's performance?

我有一个处理非常大数据的 Silverstripe 网站。我做了一个 API,return 是一个非常大的转储,我在前端通过 ajax 调用它 API。

当 ajax 调用 API 时,数据到 return 需要 10 分钟(json 数据很长,客户接受了)。

当他们在等待数据 return 时,他们在另一个选项卡中打开同一个站点来做其他事情,但是在上一个 ajax 请求完成之前,该站点非常慢。

在等待大 json 数据时,我能做些什么来避免一切都没有响应吗?

这是代码及其作用的解释:

我创建了一个名为 geteverything 的方法,它驻留在 Web 服务器上,如下所示,它访问另一台服务器(数据服务器)以通过流 API(位于数据服务器中)获取数据。数据量大,数据服务器慢;我的客户不介意请求花费很长时间,他们介意其他一切变得多慢。会话用于确定请求的细节。

protected function geteverything($http, $id) {
    if(($System = DataObject::get_by_id('ESM_System', $id))) {
        if(isset($_GET['AAA']) && isset($_GET['BBB']) && isset($_GET['CCC']) && isset($_GET['DDD'])) {
            /**
              --some condition check and data format for AAA BBB CCC and DDD goes here
            **/
            $request = "http://dataserver/streaming?method=xxx";
            set_time_limit(120);
            $jsonstring = file_get_contents($request);
            echo($jsonstring);
        }
    }
}

我该如何解决这个问题,或者您还需要了解什么才能提供帮助?

花费这么长时间的原因是您将 json 的完整内容下载到您的服务器,然后将其全部发送给用户。在开始发送之前无需等待您获取整个文件。

而不是使用 file_get_contents 与 curl 建立连接并将输出直接写入 php://output

例如,此脚本将原样复制 http://example.com/

<?php

    // Initialise cURL. You can specify the URL in curl_setopt instead if you prefer
    $ch = curl_init("http://example.com/");

    // Open a file handler to PHP's output stream
    $fp = fopen('php://output', 'w');    

    // Turn off headers, we don't care about them
    curl_setopt($ch, CURLOPT_HEADER, 0);

    // Tell curl to write the response to the stream
    curl_setopt($ch, CURLOPT_FILE, $fp);

    // Make the request
    curl_exec($ch);

    // close resources
    curl_close($ch);
    fclose($fp);