LoginSignup
12
6

More than 5 years have passed since last update.

DartでHttpリクエストをリトライ

Posted at

 Dart Advent Calendar 2018 20日目の記事です。
 
 FlutterでもAngularDartでもDartでHttpのリクエスト処理を書く事は多いと思います。その際にリトライ処理が必要になったりする事ってあると思うんですが、普通に書こうとすると結構面倒ですよね。今回はそんなHttpのリトライ処理を簡単に書けるライブラリーを紹介します。
 

依存関係を追加

 httpクライアントのライブラリーとリトライ処理のライブラリーを依存関係に追加します。

pubspec.yaml
dependencies:
  http: ^0.12.0 #ここを追加
  http_retry: ^0.1.1+3 #ここを追加

使い方

 使い方は簡単でhttpライブラリーのClient(Webの場合はBrowserClient)をRetryClientでラップするだけです。

void main() async {
  var client = new RetryClient(new Client());
  var response = await client.get("http://localhost:8080/");
  print(response.body);
  client.close();
}

 デフォルトで下記の動作になります。

  • リトライ回数の上限は3回
  • 2回目のリトライまでに500ミリ待ち、以降は前回に待ったミリ秒に1.5倍したミリ秒待つ
  • リトライするのはレスポンスが503のステータスコードの場合

いろいろ調整

 RetryClientの引数でいろいろ動作を調整することが出来ます。

void main() async {
  var client = new RetryClient(
      new Client(),
      retries: 5,
      when: (response) => response.statusCode == 404,
      whenError: (dynamic error, StackTrace stackTrace) {
        print(stackTrace);
        return true; //falseを返した場合はリトライしない
      },
      onRetry: (BaseRequest request, BaseResponse response, int retryCount) => print("retry!")
  );
  var response = await client.get("http://localhost:8080/");
  print(response.statusCode);
  client.close();
}

上記の場合だと

  • リトライ回数は5回(retries)
  • レスポンスのステータスコードが404の場合にリトライをする(when)
  • リクエストに失敗した場合にStackTraceを出力し、リトライを実行(whenError)
  • リトライ時に 「retry!」 と出力する(onRetry)

どうでしょうか。愚直に書くと結構面倒なリトライ処理がかなり簡潔に書けるようになると思います。

12
6
0

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
12
6