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

Phu*_* Le 5 php ajax silverstripe

我有一个Silverstripe网站,处理非常大的数据.我创建了一个返回非常大的转储的API,我通过ajax get在前端调用该API.

当ajax调用API时,返回数据需要10分钟(非常长的json数据和客户接受的数据).

当他们等待数据返回时,他们在另一个选项卡中打开相同的站点来执行其他操作,但在上一个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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Dan*_*elM 3

花费这么长时间的原因是您将整个 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);
Run Code Online (Sandbox Code Playgroud)