学无先后,达者为师

网站首页 编程语言 正文

使用Guzzle拓展包请求接口失败重试

作者:渡目成书 更新时间: 2022-01-26 编程语言
  • 问题在接口不稳定的情况下,可能出现访问接口错误情况,一般又在第二次请求又会成功。这种时候需要我们完成一个重试的策略去进行规避
  • 解决:使用guzzle中间的重试去解决
<?php
require './vendor/autoload.php';

class Retry
{
    const MAX_RETRIES = 2;
    public $client;

    public function __construct()
    {
        $handlerStack = \GuzzleHttp\HandlerStack::create(new  \GuzzleHttp\Handler\CurlHandler());
        $handlerStack->push(\GuzzleHttp\Middleware::retry($this->retryDecider(), $this->retryDelay()));
        $this->client = new \GuzzleHttp\Client(['handler' => $handlerStack]);
    }

    public function retryDecider()
    {
        return function (
            $retries,
            \GuzzleHttp\Psr7\Request $request,
            \GuzzleHttp\Psr7\Response $response = null,
            \GuzzleHttp\Exception\RequestException $exception = null
        ) {
            if ($retries >= self::MAX_RETRIES) {
                var_dump('次数'.$retries);//查看
                return false;
            }
            if ($exception instanceof \GuzzleHttp\Exception\ConnectException) {
                return true;
            }

            if ($response) {
                // 如果请求有响应,但是状态码大于等于500,继续重试(这里根据自己的业务而定)
                if ($response->getStatusCode() >= 200) {
                    return true;
                }
            }

            return false;
        };
    }

    protected function retryDelay()
    {
        return function ($numberOfRetries) {
            return 1000 * $numberOfRetries;
        };
    }
}


class PostHttp
{
    public function aa()
    {
        $retry = new Retry();

        return $retry->client->request('GET', 'http://boot.test/api/test');
    }
}

$obj = new PostHttp();

$t = $obj->aa();

var_dump($t);
  • 设置访问接口返回200进行重试2次,结果重试2次达到了效果
    在这里插入图片描述

原文链接:https://blog.csdn.net/weixin_43674113/article/details/121378995

栏目分类
最近更新