Zer*_*rce 7 php middleware http guzzle6
我在Laravel 5.2中编写了一些代码来从不可靠的API源中检索结果.但是,它需要能够在失败尝试时自动重试请求,因为API调用在大约三分之一的时间内导致503.
我使用Guzzle来做这件事,我想我知道在处理之前将代码拦截503响应的位置; 但我不确定在那里写什么.
就重试而言,guzzle文档提供的内容并不多,而我在Guzzle 6中遇到的所有示例都只显示了如何检索结果(我已经可以做到),而不是如何让它重复如有需要请求.
我绝不会要求任何人为我做这项工作 - 但我认为我正在接近我对此的理解极限.如果有人能指出我正确的方向,那将非常感激:)
编辑:
我会尝试修改.请考虑以下代码.在其中,我想发送一个通常应该产生JSON响应的GET请求.
DataController.php
$client = new \GuzzleHttp\Client();
$request = $client->request('GET', 'https://httpbin.org/status/503'); // URI is for testing purposes
Run Code Online (Sandbox Code Playgroud)
当此请求的响应为503时,我可以在此拦截它:
Handler.php
public function render($request, Exception $e)
{
if ($e->getCode() == 503)
{
// Code that would tell Guzzle to retry the request 5 times with a 10s delay before failing completely
}
return parent::render($request, $e);
}
Run Code Online (Sandbox Code Playgroud)
我不知道那是最好放的地方,但真正的问题是我不知道里面写的是什么 if ($e->getCode() == 503)
默认情况下,当返回非 2** 响应时,Guzzle 会引发异常。在您的情况下,您会看到 503 响应。异常可以被认为是应用程序可以恢复的错误。它的工作方式是使用try catch块。
try {
// The code that can throw an exception will go here
throw new \Exception('A generic error');
// code from here down won't be executed, because the exception was thrown.
} catch (\Exception $e) {
// Handle the exception in the best manner possible.
}
Run Code Online (Sandbox Code Playgroud)
您将可能引发异常的代码包装在try块的部分中。catch然后,您在该块的部分中添加错误处理代码。您可以阅读上面的链接以获取有关 php 如何处理异常的更多信息。
对于您的情况,让我们将 Guzzle 调用移至控制器中它自己的方法:
public function performLookUp($retryOnError = false)
{
try {
$client = new \GuzzleHttp\Client();
$request = $client->request('GET', 'https://httpbin.org/status/503');
return $request->send();
} catch (\GuzzleHttp\Exception\BadResponseException $e) {
if ($retryOnError) {
return $this->performLookUp();
}
abort(503);
}
}
Run Code Online (Sandbox Code Playgroud)
现在在您的控制器中您可以执行,$this->performLookUp(true);.