Limit connecting time with Guzzle HTTP PHP client

橙三吉。 提交于 2019-12-05 01:26:54
phpisuber01

Here's the updated solution to this problem for Guzzle version (Guzzle 4).

$request = $client->get(sprintf("%s/noisesize.api", $this->noiseConfig->url), [
    'timeout' => 5, // Response timeout
    'connect_timeout' => 5, // Connection timeout
]);

Throws Guzzle\Http\Exception\RequestException

Documentation for the latest version is here: Guzzle request options - connect_timeout, timeout.

Small precision, you also can define timeouts on Client constructor

$client = new Guzzle\Http\Client('', array(
    'request.options' => array (
        'timeout' => 6,
        'connect_timeout' => 6 
    ) 
));

It'll be valid for all requests made from this Client

The only way I know how to do it in Guzzle is:

$params = array(
    'command.request_options' = array(
        'timeout'         => 5,
        'connect_timeout' => 2
    )
);

$client = new Client();

$description = ServiceDescription::factory('/path/to/service/description/file');
$client->setDescription($description);

$command = $client->getCommand('commandName', $params);
$command->prepare();

$client->execute($command);

At first glance, Guzzle's documentation seems very good, but I think it's poor, confusing and incomplete. So, for me, is hard to figure out if your code is actually correct and if it should work.

Your example is correct, but it will always fail.

The error is happening on cURL level, not Guzzle. Before sending an HTTP request (Guzzle's job), you need to establish the related IP session (cURL's one). To get the IP session, DNS translation must happen before packets are sent.

In your example, DNS resolution is failing. It is happening in cURL code, not Guzzle one. So your timeout value won't be used.

If you're still having this error with your real URL, you may add, before your guzzle request, a test which will check if DNS is resolved. Or you may define the following cURL option: CURLOPT_CONNECTTIMEOUT or CURLOPT_CONNECTTIMEOUT_MS (see http://php.net/manual/en/function.curl-setopt.php)

Set dns resolve timeout before use guzzle client

putenv('RES_OPTIONS=retrans:1 retry:1 timeout:1 attempts:1'); //dns resolve params

$request = $client->get(sprintf("%s/noisesize.api", $this->noiseConfig->url), 
array(
'timeout' => 5, // Response timeout
'connect_timeout' => 5, // Connection timeout
));
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!