cURL 错误 28:操作在 2000 毫秒后超时,收到 23000995 个字节中的 7276200 个字节

kyo*_*kyo 4 php laravel guzzle laravel-5

描述

我在我的 Laravel 项目中使用 Guzzle。当我向返回大量有效负载的 API 发出请求时,我遇到了内存崩溃。

我在CURL.php班级中名列前茅。我有使用 Guzzle 的 get()。

use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client;
use GuzzleHttp\FORCE_IP_RESOLVE;
use GuzzleHttp\DECODE_CONTENT;
use GuzzleHttp\CONNECT_TIMEOUT;
use GuzzleHttp\READ_TIMEOUT;
use GuzzleHttp\TIMEOUT;

class CURL {

    public static function get($url) {

        $client = new Client();
        $options = [
            'http_errors' => true,
            'force_ip_resolve' => 'v4',
            'connect_timeout' => 2,
            'read_timeout' => 2,
            'timeout' => 2,
        ];
        $result = $client->request('GET',$url,$options);
        $result = (string) $result->getBody();
        $result = json_decode($result, true);
        return $result;

    }

    ...

}
Run Code Online (Sandbox Code Playgroud)

当我在我的应用程序中这样调用它时,它请求一个大的有效负载 (30000)

$url = 'http://site/api/account/30000';
$response =  CURL::get($url)['data'];
Run Code Online (Sandbox Code Playgroud)

我一直收到这个错误

cURL 错误 28:操作在 2000 毫秒后超时,收到 23000995 个字节中的 7276200 个(参见http://curl.haxx.se/libcurl/c/libcurl-errors.html

我如何避免这种情况?

我应该增加这些设置吗?

'connect_timeout' => 2,
'read_timeout' => 2,
'timeout' => 2,
Run Code Online (Sandbox Code Playgroud)

Ale*_*kov 7

是的,您需要增加read_timeouttimeout。错误很明显,您没有足够的时间来获得响应(服务器很慢,网络或其他什么都无所谓)。

如果可能,增加超时是最简单的方法。

如果服务器支持分页,那么逐部分请求数据是一种更好的方式。

您还可以在 Guzzle 中使用异步查询,并在等待 API 响应时向最终用户发送一些内容。