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

时间:2015-07-23 02:27:09

标签: 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);
        }
    }
}

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

1 个答案:

答案 0 :(得分: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);
相关问题