限制与 Guzzle HTTP PHP 客户端的连接时间

2022-08-31 00:11:08

我正在使用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是一个真正的网址,在这里改变了它)


答案 1

以下是Guzzle版本(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

最新版本的文档在这里:Guzzle请求选项 - connect_timeout超时


答案 2

精度小,还可以在客户端构造函数上定义超时

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

它对来自此客户端的所有请求都有效


推荐