问题描述
我正在使用Guzzle打开url-s列表并获取标题.有些网址响应时间过长,无法打开,我想忽略它们. Guzzle抛出异常最多需要20秒钟以上的时间,我想更改此异常并将连接时间限制为2秒.我有这段代码,但仍然需要更长的时间:
I'm using Guzzle to open a list of url-s and get the headers. Some of the urls are taking too long to respond and can't be openned and i want to ignore them. It takes me up to 20+ seconds before Guzzle throws an exception and i want to change this and limit the time for connecting to 2 sec. I have this code but it still takes much longer:
<?php
include 'vendor/autoload.php';
$start = new \DateTime("now");
$start = $start->format("d.m.Y H:i:s");
echo $start."\n";
$client = new Guzzle\Http\Client();
Guzzle\Http\StaticClient::mount();
try {
$request = $client->get('http://takestoolongexample', [], ['connect_timeout' => 2, 'timeout' => 3, 'debug' => true]);
$response = $request->send();
var_dump($response->getStatusCode());
} catch (Exception $e) {
echo "\n".$e->getMessage()."\n";
}
$end = new \DateTime("now");
$end = $end->format("d.m.Y H:i:s");
echo "\n".$end."\n";
?>
这是一个示例结果.如您所见,花了13秒.
Here's an example result. As you can see, it took 13 seconds.
$ php test.php
30.12.2013 22:00:07
* getaddrinfo(3) failed for takestoolongexample:80
* Couldn't resolve host 'takestoolongexample'
* Closing connection 0
[curl] 6: Couldn't resolve host 'http://takestoolongexample' http://takestoolongexample
30.12.2013 22:00:20
(http://takestoolongexample
是真实的URL,请在此处更改)
(http://takestoolongexample
was a real url, changed it here)
推荐答案
这是针对Guzzle版本(Guzzle 4)的此问题的更新解决方案.
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
]);
抛出Guzzle\Http\Exception\RequestException
最新版本的文档位于:枪口请求选项- connect_timeout ,超时.
Documentation for the latest version is here: Guzzle request options - connect_timeout, timeout.
这篇关于限制与Guzzle HTTP PHP客户端的连接时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!