我正在使用 Guzzle 打开一个 url-s 列表并获取标题。有些网址响应时间过长,无法打开,我想忽略它们。在 Guzzle 引发异常之前,我最多需要 20 多秒,我想更改它并将连接时间限制为 2 秒。我有这个代码,但它仍然需要更长的时间:
<?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 秒。
$ 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
是一个真实的网址,在这里更改)