【问题标题】:Laravel Response::json() exhausts memoryLaravel Response::json() 耗尽内存
【发布时间】:2016-08-31 02:59:15
【问题描述】:

我有一个有时会返回 HTML 块的应用程序;在这种情况下,我必须返回一个大表并且内存耗尽。

我设置了一个宏,它检查要返回的数据不大于允许的 json 限制;

Response::macro('jsonWithValidation', function($response) {
    if(strlen(serialize($response)) > 125000000)
        $response = array(
            'status' => 200,
            'execute_also' => array(
                'notify("warning", "Data too large to be sent over json");'
            )
        );

    return Response::json($response, $response['status']);
});

这个脚本很有魅力;我现在面临的问题是最后一个Response::json 耗尽内存。这意味着我的响应不会太大而无法通过 json 发送,但是 Laravel 方法(我正在运行 Laravel 4.2)会导致一切崩溃。

理想情况下,在代码的这一点上,我可以有两个选择:

  • 用基本的php发送所有东西,但我相信Laravel的功能已经很基本了
  • 清除我不需要响应的内存

理想情况下我想使用第二个选项,但我不知道是否可以这样做...所以我应该怎么做才能避免超出内存限制?

编辑: 这是我得到的错误

[05-May-2016 14:19:42 Europe/Rome] PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 64 bytes) in C:\wamp\www\project_ski\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php on line 446

【问题讨论】:

  • 您进行了检查,但还是生成了 JSON!如果检查失败,请不要这样做。

标签: php json laravel laravel-4.2


【解决方案1】:

这个json大小限制到底是什么性质,为什么觉得需要实现?

serialize() 不会生成 json 数据,因此您甚至没有检查您声称的相同内容。此外,您正在运行两次相同的繁重操作。

更好的方法是这样的:

Response::macro('jsonWithValidation', function($response) {

    $return = Response::json($response, $response['status']);

    if(strlen($return) > 125000000)
        $return = array(
            'status' => 200,
            'execute_also' => array(
                'notify("warning", "Data too large to be sent over json");'
            )
        );

    return $return;
});

此外,如果您返回错误,http 状态代码不应为 200 OK。更多内容:http://www.restapitutorial.com/httpstatuscodes.html

【讨论】:

    【解决方案2】:

    我不确定。如果您觉得内存只是您的问题,请根据您的响应大小设置内容长度。

        $response = Response::make($contents, $response['status']);
        $response->header('Content-Length', strlen(serialize($response));
        $response->header('Content-Type', 'json');
    
    return $response;
    

    【讨论】:

      猜你喜欢
      • 2020-06-02
      • 2020-02-05
      • 1970-01-01
      • 2015-08-23
      • 2012-11-10
      • 2012-08-19
      • 2011-02-09
      • 2015-10-01
      • 2018-12-11
      相关资源
      最近更新 更多