LoginSignup
13
13

More than 5 years have passed since last update.

GuzzleのMiddleware::retryを使ってみた

Last updated at Posted at 2015-12-27

Guzzleを使ってリトライ処理をしたかった
Guzzleでは
https://github.com/guzzle/guzzle/blob/master/src/Middleware.php#L163
が使えるようだ。

※利用方法が間違っていたのでコードを直しました。
参考にしたサイト http://addshore.com/2015/12/guzzle-6-retry-middleware/

使ってみた。

php
//リトライ判断
$decider = function ($retries, $request, $response, $exception) {
    if ($retries >= 3) {
        return false;
    }

    if ($exception instanceof ConnectException) {
        return true;
    }

    if ($response && $response->getStatusCode() != '200') {
        return true; //リトライさせる場合はtrueを返す
    }

    return false;
};

//遅延させたい場合
$delay = function ($retries) {
    return 1; //ミリ秒で返す。
};

$retry = Middleware::retry($decider, $delay);

$stack = new HandlerStack();
$stack->setHandler(new CurlHandler());
$stack->push($retry);
$this->client = new Client(['base_uri' => $base_uri, 'verify' => $verify, 'handler' => $stack]);

分かったこと・出来たこと

  • リトライが出来た!
  • リトライ時にリクエストのheaderの中身をいじろうとしたが変更できなかった。

結論

  • 400系500系のエラーの場合に、もう一度同じ内容でリトライする場合には使える
  • リクエストを書き換えてリトライさせる場合は使えない(書き換えられるなら教えてください。)

分かったこと追加

  • 処理回数をカウントするようにしていたが$retriesを使うべき
  • $responseがnullで来る場合があるのでチェックが必要
  • 接続に失敗した場合ConnectExceptionが$exceptionで渡される
13
13
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
13