For AI agents: the complete documentation index is available at /Practical-Introduction-to-Spring-Boot/llms.txt, the full documentation bundle is available at /Practical-Introduction-to-Spring-Boot/llms-full.txt, and this page is available as Markdown at /Practical-Introduction-to-Spring-Boot/SpringBoot入門/リトライ入門.md.

Spring Boot リトライ入門 — 条件・回数・待ち時間

講義の区切り

基本編の目安は 60 分です。終了条件は、配送 API が 503 を 2 回返したあと、3 回目の呼び出しで送料を取得できることです。 さらに、再試行の上限を減らした場合と、再試行の対象外のエラーが返った場合を、模擬 API のログで確認します。

概要

外部 API 連携入門 の送料照会アプリに、Spring Framework の RetryTemplate を使ったリトライを追加します。 利用者は送料照会アプリに GET を 1 回送ります。配送 API が一時的に 503 を返すと、送料照会アプリが配送 API への GET を再試行します。

事前準備

  • 外部 API 連携入門の完成版(送料照会アプリと MockShippingApi.java)
  • JDK 21 と Spring Boot 4.0 系
  • 空きポート 8080(送料照会アプリ)、8089(模擬配送 API)

前章のプロジェクトをそのまま使います。RetryTemplate は Spring Framework 7 の機能で、前章の依存関係で利用できます。 前章のプロセスが起動中なら、作業を始める前に Ctrl+C で停止します。

触って学ぶリトライ

模擬配送 API に一時エラーを追加する

プロジェクトのルートにある MockShippingApi.java の import に、次の 2 行を追加します。

import java.time.Instant;
import java.util.concurrent.atomic.AtomicInteger;

MockShippingApi クラスの先頭に、flaky を照会した回数を数えるフィールドを追加します。

private static final AtomicInteger FLAKY_CALLS = new AtomicInteger();

handleRate の switch (path) に、次の case を追加します。 模擬 API の起動後、/rates/flaky への最初の 2 回の GET に 503 を返し、3 回目以降は 200 と送料を返します。

flaky の case
case "/rates/flaky" -> {
  int call = FLAKY_CALLS.incrementAndGet();
  int status = call <= 2 ? 503 : 200;
  System.out.printf("%s GET %s call=%d -> %d%n", Instant.now(), path, call, status);
  if (status == 503) {
    sendJson(exchange, 503, """
        {"error":"shipping service temporarily unavailable"}
        """);
  } else {
    sendJson(exchange, 200, """
        {"area":"flaky","feeYen":700}
        """);
  }
}

handleRate の先頭にある既存のログ出力は、次のように置き換えます。flaky の GET には、追加した case が回数と結果を記録します。

if (!"/rates/flaky".equals(path) || !"GET".equals(exchange.getRequestMethod())) {
  System.out.println(exchange.getRequestMethod() + " " + path);
}

1 つ目のターミナルで模擬配送 API を起動します。

java MockShippingApi.java

以降、flaky の実験を始めるたびに、模擬 API を Ctrl+C で停止し、同じコマンドで起動し直します。 起動し直すと回数が 0 に戻ります。実験中は送料照会アプリの 8080 番ポートにリクエストを送り、8089 番の模擬 API に直接 GET を送る操作は挟まないでください。

503 のときだけ再試行する

src/main/resources/application.yaml の shipping セクションを次の内容に置き換えます。 初回を含めて最大 3 回、試行の間には 500 ミリ秒待つ設定です。

shipping の設定
shipping:
  base-url: http://127.0.0.1:8089
  connect-timeout: 1s
  read-timeout: 1s
  retry:
    max-retries: 2
    delay: 500ms

src/main/java/dev/mikoto2000/springboot/shipping/ShippingClient.java を次のコードに置き換えます。 配送 API を呼び出す処理を fetchQuote に取り出し、RetryTemplate で実行します。

ShippingClient.java
package dev.mikoto2000.springboot.shipping;

import java.net.SocketTimeoutException;
import java.time.Duration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.retry.RetryPolicy;
import org.springframework.core.retry.RetryTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.RestClientResponseException;
import org.springframework.web.server.ResponseStatusException;

@Component
public class ShippingClient {

  private final RestClient restClient;
  private final RetryTemplate retryTemplate;

  public ShippingClient(
      RestClient.Builder builder,
      @Value("${shipping.base-url}") String baseUrl,
      @Value("${shipping.connect-timeout}") Duration connectTimeout,
      @Value("${shipping.read-timeout}") Duration readTimeout,
      @Value("${shipping.retry.max-retries}") long maxRetries,
      @Value("${shipping.retry.delay}") Duration retryDelay) {
    var factory = new SimpleClientHttpRequestFactory();
    factory.setConnectTimeout(connectTimeout);
    factory.setReadTimeout(readTimeout);
    this.restClient = builder.baseUrl(baseUrl).requestFactory(factory).build();

    RetryPolicy retryPolicy = RetryPolicy.builder()
        .includes(HttpServerErrorException.ServiceUnavailable.class)
        .maxRetries(maxRetries)
        .delay(retryDelay)
        .build();
    this.retryTemplate = new RetryTemplate(retryPolicy);
  }

  public ShippingQuote getQuote(String area) {
    try {
      return retryTemplate.invoke(() -> fetchQuote(area));
    } catch (HttpClientErrorException.NotFound exception) {
      throw new ResponseStatusException(HttpStatus.NOT_FOUND, "配送対象の地域が見つかりません。", exception);
    } catch (RestClientResponseException exception) {
      throw new ResponseStatusException(HttpStatus.BAD_GATEWAY, "配送 API がエラーを返しました。", exception);
    } catch (ResourceAccessException exception) {
      if (exception.contains(SocketTimeoutException.class)) {
        throw new ResponseStatusException(HttpStatus.GATEWAY_TIMEOUT, "配送 API の呼び出しがタイムアウトしました。", exception);
      }
      throw new ResponseStatusException(HttpStatus.BAD_GATEWAY, "配送 API と通信できません。", exception);
    }
  }

  private ShippingQuote fetchQuote(String area) {
    ShippingQuote quote = restClient.get()
        .uri("/rates/{area}", area)
        .accept(MediaType.APPLICATION_JSON)
        .retrieve()
        .body(ShippingQuote.class);
    if (quote == null) {
      throw new ResponseStatusException(HttpStatus.BAD_GATEWAY, "配送 API の応答本文が空です。");
    }
    return quote;
  }
}

配送 API が 503 を返すと、RestClient は HttpServerErrorException.ServiceUnavailable を投げます。 RetryTemplate はこの例外を見て再試行を判断します。例外を送料照会アプリの HTTP 応答に変換する処理は、invoke の外側に置きます。 上限まで 503 が続くと最後の例外が呼び出し元に伝わり、前章と同じ扱いで利用者には 502 が返ります。

3 回目に成功することを確認する

2 つ目のターミナルで送料照会アプリを起動します。PowerShell では .\mvnw.cmd spring-boot:run を使います。

./mvnw spring-boot:run

起動した模擬配送 API に flaky への GET が届いていない状態で、3 つ目のターミナルから送料照会アプリへ GET を 1 回送ります。PowerShell では curl.exe を使います。

curl -sS -w '\nHTTP %{http_code}, %{time_total}s\n' http://127.0.0.1:8080/shipping-quotes/flaky

約 1 秒で、200 と {"area":"flaky","feeYen":700} が返ります。模擬 API のターミナルでは、次のように 3 回の GET を確認できます。

2026-01-01T00:00:00.000Z GET /rates/flaky call=1 -> 503
2026-01-01T00:00:00.500Z GET /rates/flaky call=2 -> 503
2026-01-01T00:00:01.000Z GET /rates/flaky call=3 -> 200

ログの時刻は例です。隣り合うログの時刻を引いて、待ち時間がおおむね 500 ミリ秒ずつ入っていることを確認します。 curl の所要時間には、2 回分の待ち時間と各 HTTP 通信の時間が含まれます。

再試行する条件を確かめる

同じ設定のまま、404、500、タイムアウトのケースを照会します。

curl -i http://127.0.0.1:8080/shipping-quotes/unknown
curl -i http://127.0.0.1:8080/shipping-quotes/maintenance
curl -i http://127.0.0.1:8080/shipping-quotes/slow
地域コード配送 API 側の動作送料照会アプリの応答模擬 API に記録される GET
unknown4044041 回
maintenance5005021 回
slow3 秒待って応答読み取りの待ち時間を超えて 5041 回

maintenance の 500 も、slow のタイムアウトもエラーですが、この設定で再試行する条件は 503 です。

回数の上限と待ち時間を変える

次の表の各行を 1 回ずつ試します。送料照会アプリを停止して YAML の shipping.retry の値を変え、再起動します。 毎回、模擬 API も起動し直してから、先ほどと同じ flaky の curl を 1 回実行してください。

max-retriesdelay模擬 API の応答順送料照会アプリの応答確認すること
0500ms503502初回だけ。再試行の待ち時間は発生しない
1500ms503 → 503502再試行は 1 回。3 回目の GET は送られない
21s503 → 503 → 200200再試行は 2 回。ログの間隔は約 1 秒になる

最後の行を、最初に試した max-retries: 2、delay: 500ms と比較します。 同じ 3 回で成功しますが、2 回分の待ち時間がそれぞれ長くなり、所要時間は約 1 秒から約 2 秒になります。

後片付け

送料照会アプリと模擬配送 API を、それぞれのターミナルで Ctrl+C を押して停止します。

座学で学ぶリトライ

条件を決める

この演習の 503 は、一時的にサービスを利用できない状況を表します。少し待てば成功する可能性があるため、再試行の対象にしました。 404 は地域コードに対応する送料がないことを示すため、同じ地域コードでの再試行は行いません。 実際に対象とするエラーは、呼び出し先の仕様と、操作をやり直したときの影響を踏まえて決めます。

送料照会の GET は読み取りです。注文登録の POST は、応答が届く前に登録だけが完了している場合があり、再試行で二重登録になることがあります。 状態を変える操作で再試行を検討する場合は、同じ要求を複数回受け取った場合の仕様を先に確認します。

初回と再試行を数える

maxRetries は、初回の失敗後に追加できる回数です。2 を指定すると最大 3 回呼び出せます。途中で成功すれば、その時点で処理を終えます。 タイムアウトは試行ごとの待ち時間に関わり、delay は試行と試行の間に入ります。 利用者が待てる時間を考えるときは、各試行の所要時間と、再試行に入る前の待ち時間を合わせて見積もります。

理解を確かめる

  1. max-retries: 1 で利用者に 502 が返るとき、模擬 API のログに 200 が現れない理由を説明する。
  2. maintenance と flaky では、どちらも配送 API が 5xx を返す。試行回数が異なる理由を説明する。
  3. flaky が 3 回目で成功する場合、delay を 500ms から 1s にすると、待ち時間の合計が何秒増えるか答える。

参考資料