Laravel - Guzzle:获取 GuzzleHttp\Exception\ConnectException:cURL 错误 6 无法随机解析主机

TJ *_*ort 4 php curl laravel-5.1

这可能是我见过的最奇怪的情况。基本上我有一个在 Laravel 5.1 中构建的系统,它需要向外部系统发出请求。问题是,有时它有效,但有时我得到

GuzzleHttp\Exception\ConnectException: cURL error 6: Could not resolve host: hosthere
Run Code Online (Sandbox Code Playgroud)

就代码而言,绝对没有任何变化。我使用完全相同的参数运行应用程序,有时会收到错误,有时会得到正确的响应。

有任何想法吗?

提前致谢

编辑2 当我执行 nslookup domainthatineedtouse.com 时,我得到

;; Got SERVFAIL reply from 8.8.8.8, trying next server
Server: 8.8.4.4
Address:    8.8.4.4#53

Non-authoritative answer:
Name:   domainthatineedtouse.com
Address: therealipaddressishere
Run Code Online (Sandbox Code Playgroud)

这可以与问题相关吗?

编辑 这是建立连接的类的一部分。

<?php


use GuzzleHttp\ClientInterface;

class MyClass
{
    const ENDPOINT = 'http://example.com/v1/endpoint';

    /**
     * @var \GuzzleHttp\ClientInterface
     */
    protected $client;

    /**
     * @var string The api key used to connect to the service
     */
    protected $apiKey;

    /**
     * Constructor.
     *
     * @param $apiKey
     * @param ClientInterface $client
     */
    public function __construct($apiKey, ClientInterface $client)
    {
        $this->client = $client;
        $this->apiKey = $apiKey;
    }

    /**
     * Here is where I make the request
     *
     * @param $param1
     * @param $param2
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function makeTheRequest($param1, $param2)
    {
        return $this->client->request('get', self::ENDPOINT, [
            'query' => [
                'api_token' => $this->apiKey,
                'parameter_1' => $param1,
                'parameter_2' => $param2,
            ]
        ]);
    }
}
Run Code Online (Sandbox Code Playgroud)

Tar*_*han 7

这是人们在调用外部 API 时应该始终预见到的事情,大多数外部 API 都会面临中断,包括非常流行的亚马逊产品广告 API。因此请记住,这应该始终放置在 try/catch 中,并使用放置在 do/while 中的重试。

您应该始终捕获这两种类型的常见超时:连接超时和请求超时。\GuzzleHttp\Exception\ConnectException\GuzzleHttp\Exception\RequestException

// query External API
// retry by using a do/while
$retry_count    = 0;
do {
    try {
        $response = json_decode($this->external_service->runOperation($operation));
    } catch (\GuzzleHttp\Exception\ConnectException $e) {
        // log the error here

        Log::Warning('guzzle_connect_exception', [
                'url' => $this->request->fullUrl(),
                'message' => $e->getMessage()
        ]);
    } catch (\GuzzleHttp\Exception\RequestException $e) {

        Log::Warning('guzzle_connection_timeout', [
                'url' => $this->request->fullUrl(),
                'message' => $e->getMessage()
        ]);
    }

    // Do max 5 attempts
    if (++$retry_count == 5) {
        break;
    }
} while(!is_array($response));
Run Code Online (Sandbox Code Playgroud)