使用GuzzleHTTP时如何检查端点是否正常工作 [英] How to check if endpoint is working when using GuzzleHTTP

查看:121
本文介绍了使用GuzzleHTTP时如何检查端点是否正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在使用guzzleHttp,我可以得到我想要的响应并捕获错误.

So I am working with guzzleHttp and I can get the responses that I am after and catch errors.

我唯一的问题是,如果基本URI错误,整个脚本就会失败...我该如何进行某种检查以确保端点确实在运行?

The only problem I am having is that if the base URI is wrong, the whole script fails... how can I do some sort of checking to make sure that the endpoint is actually up?

$client = new GuzzleHttp\Client(['base_uri' => $url]);

推荐答案

您的查询可能会遇到很多问题,不仅是端点已关闭.查询时服务器上的网络接口可能会立即关闭,DNS可能会关闭,到主机的路由可能不可用,连接超时等.

You might have many issues with your query, not only that the endpoint is down. Network interface on your server can go down right at the moment of query, DNS can go down, a route to the host might not be available, a connection timeout, etc.

因此,您一定要为许多问题做好准备.我通常会捕获一般的RequestException并执行某些操作(日志记录,针对应用程序的特定处理),如果我应该以不同的方式处理它们,还会捕获特定的异常.

So you definitely should be ready for many issues. I usually catch a general RequestException and do something (logging, app specific handling), plus catch specific exceptions if I should handle them differently.

此外,还有许多用于错误处理的现有模式(和解决方案).例如,通常在端点不可用时重试查询.

Also, there are many existing patterns (and solutions) for error handling. For example, it's usual to retry a query is an endpoint is unavailable.

$stack = HandlerStack::create();
$stack->push(Middleware::retry(
    function (
        $retries,
        RequestInterface $request,
        ResponseInterface $response = null,
        RequestException $exception = null
    ) {
        // Don't retry if we have run out of retries.
        if ($retries >= 5) {
            return false;
        }

        $shouldRetry = false;
        // Retry connection exceptions.
        if ($exception instanceof ConnectException) {
            $shouldRetry = true;
        }
        if ($response) {
            // Retry on server errors.
            if ($response->getStatusCode() >= 500) {
                $shouldRetry = true;
            }
        }

        // Log if we are retrying.
        if ($shouldRetry) {
            $this->logger->debug(
                sprintf(
                    'Retrying %s %s %s/5, %s',
                    $request->getMethod(),
                    $request->getUri(),
                    $retries + 1,
                    $response ? 'status code: ' . $response->getStatusCode() :
                        $exception->getMessage()
                )
            );
        }

        return $shouldRetry;
    }
));

$client = new Client([
    'handler' => $stack,
    'connect_timeout' => 60.0, // Seconds.
    'timeout' => 1800.0, // Seconds.
]);

这篇关于使用GuzzleHTTP时如何检查端点是否正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆