我在 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;
}
...
}
当我在我的应用程序中这样调用它时,它会请求一个大的负载 (30000)
$url = 'http://site/api/account/30000';
$response = CURL::get($url)['data'];
我一直收到这个错误
cURL error 28: Operation timed out after 2000 milliseconds with 7276200 out of 23000995 bytes received (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)
如何避免这种情况?
我应该增加这些设置吗?
'connect_timeout' => 2,
'read_timeout' => 2,
'timeout' => 2,
最佳答案
是的,你需要增加read_timeout和timeout。错误很明显,你没有足够的时间得到响应(服务器很慢,网络或其他什么的,无所谓)。
如果可能,增加超时是最简单的方法。
如果服务器支持分页,那么逐个请求数据是一种更好的方式。
您还可以在 Guzzle 中使用异步查询,并在等待 API 响应时向您的最终用户发送一些内容。
关于php - curl 错误 28 : Operation timed out after 2000 milliseconds with 7276200 out of 23000995 bytes received,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46897627/