Class Retry<T>

java.lang.Object
cloud.opencode.base.core.retry.Retry<T>
Type Parameters:
T - the result type - 结果类型

public final class Retry<T> extends Object
Retry - General purpose retry utility with configurable backoff strategies 重试工具 - 通用重试工具,支持可配置的退避策略

Provides a fluent builder API for configuring retry behavior including max attempts, backoff strategy, retry predicates, and callbacks.

提供流式构建器 API 来配置重试行为,包括最大尝试次数、退避策略、重试谓词和回调。

Usage Examples | 使用示例:

// Simple retry with defaults (3 attempts, 100ms fixed delay)
String data = Retry.execute(() -> fetchData());

// Builder pattern
String result = Retry.of(() -> httpClient.get(url))
    .maxAttempts(5)
    .backoff(BackoffStrategy.exponential(Duration.ofMillis(200), 2.0))
    .retryOn(IOException.class)
    .onRetry((attempt, ex) -> log.warn("Retry #{}: {}", attempt, ex.getMessage()))
    .maxDelay(Duration.ofSeconds(30))
    .execute();

// Result-based retry (retry when result is null)
String value = Retry.of(() -> cache.get(key))
    .retryOnResult(Objects::isNull)
    .maxAttempts(5)
    .execute();

// Async retry
CompletableFuture<String> future = Retry.of(() -> fetchData())
    .maxAttempts(3)
    .executeAsync();

// Timeout across all attempts
String data = Retry.of(() -> slowService.call())
    .timeout(Duration.ofSeconds(30))
    .maxAttempts(10)
    .execute();

Thread Safety | 线程安全:

Retry instances are NOT thread-safe. Create a new instance for each execution context.

Retry 实例不是线程安全的。请为每个执行上下文创建新实例。

Since:
JDK 25, opencode-base-core V1.0.3
Author:
Leon Soo www.LeonSoo.com
See Also:
  • Method Details

    • of

      public static <T> Retry<T> of(Callable<T> task)
      Create a new Retry builder for the given task. 为给定任务创建新的 Retry 构建器。
      Type Parameters:
      T - the result type - 结果类型
      Parameters:
      task - the task to retry - 要重试的任务
      Returns:
      a new Retry builder - 新的 Retry 构建器
    • maxAttempts

      public Retry<T> maxAttempts(int maxAttempts)
      Set the maximum number of attempts (including the initial attempt). 设置最大尝试次数(包括初始尝试)。
      Parameters:
      maxAttempts - max attempts, must be >= 1 - 最大尝试次数,必须 >= 1
      Returns:
      this builder - 当前构建器
    • backoff

      public Retry<T> backoff(BackoffStrategy backoff)
      Set the backoff strategy. 设置退避策略。
      Parameters:
      backoff - the backoff strategy - 退避策略
      Returns:
      this builder - 当前构建器
    • delay

      public Retry<T> delay(Duration delay)
      Set a fixed delay between retries (convenience for backoff(BackoffStrategy.fixed(delay))). 设置重试之间的固定延迟(backoff(BackoffStrategy.fixed(delay)) 的便捷方法)。
      Parameters:
      delay - the fixed delay - 固定延迟
      Returns:
      this builder - 当前构建器
    • exponentialBackoff

      public Retry<T> exponentialBackoff(Duration initialDelay, double multiplier)
      Set an exponential backoff strategy (convenience method). 设置指数退避策略(便捷方法)。
      Parameters:
      initialDelay - the initial delay - 初始延迟
      multiplier - the multiplier - 乘数
      Returns:
      this builder - 当前构建器
    • maxDelay

      public Retry<T> maxDelay(Duration maxDelay)
      Set the maximum delay cap. If the computed delay exceeds this, it will be capped. 设置最大延迟上限。如果计算的延迟超过此值,将被截断。
      Parameters:
      maxDelay - the maximum delay - 最大延迟
      Returns:
      this builder - 当前构建器
    • timeout

      public Retry<T> timeout(Duration timeout)
      Set a total timeout for all retry attempts combined. If the timeout is exceeded, the retry loop stops and throws the last exception. 设置所有重试尝试的总超时时间。如果超时,重试循环停止并抛出最后一个异常。
      Parameters:
      timeout - the total timeout duration - 总超时时间
      Returns:
      this builder - 当前构建器
    • retryOn

      public Retry<T> retryOn(Predicate<Throwable> predicate)
      Set a predicate to determine if a given exception should trigger a retry. 设置谓词以确定给定异常是否应触发重试。
      Parameters:
      predicate - the retry predicate - 重试谓词
      Returns:
      this builder - 当前构建器
    • retryOn

      public Retry<T> retryOn(Class<? extends Throwable> exceptionType)
      Set the exception type to retry on (convenience for retryOn(type::isInstance)). 设置要重试的异常类型(retryOn(type::isInstance) 的便捷方法)。
      Parameters:
      exceptionType - the exception class to retry on - 要重试的异常类
      Returns:
      this builder - 当前构建器
    • retryOnAny

      @SafeVarargs public final Retry<T> retryOnAny(Class<? extends Throwable>... exceptionTypes)
      Set multiple exception types to retry on. Retries if the exception is an instance of any of the given types. 设置多个要重试的异常类型。如果异常是给定类型中的任意一个实例,则进行重试。
      Parameters:
      exceptionTypes - the exception classes to retry on - 要重试的异常类列表
      Returns:
      this builder - 当前构建器
    • retryOnResult

      public Retry<T> retryOnResult(Predicate<T> predicate)
      Set a predicate to retry based on the task result. When the result matches the predicate, the task is retried even though no exception was thrown. 设置基于结果的重试谓词。当结果匹配谓词时,即使未抛出异常也会重试。

      Usage | 用法:

      // Retry when result is null
      Retry.of(() -> cache.get(key))
          .retryOnResult(Objects::isNull)
          .execute();
      
      // Retry when list is empty
      Retry.of(() -> query.list())
          .retryOnResult(List::isEmpty)
          .execute();
      
      Parameters:
      predicate - the result predicate - returns true when the result should trigger a retry 结果谓词 - 当结果应触发重试时返回 true
      Returns:
      this builder - 当前构建器
    • abortIf

      public Retry<T> abortIf(Predicate<Throwable> predicate)
      Set a predicate to abort retry immediately when matched. Takes precedence over retryOn. 设置谓词,匹配时立即中止重试。优先级高于 retryOn
      Parameters:
      predicate - the abort predicate - 中止谓词
      Returns:
      this builder - 当前构建器
    • abortOn

      public Retry<T> abortOn(Class<? extends Throwable> exceptionType)
      Set the exception type to abort retry immediately. Takes precedence over retryOn. 设置遇到该异常类型时立即中止重试。优先级高于 retryOn
      Parameters:
      exceptionType - the exception class to abort on - 要中止重试的异常类
      Returns:
      this builder - 当前构建器
    • onRetry

      public Retry<T> onRetry(BiConsumer<Integer, Throwable> listener)
      Set a callback invoked before each retry attempt. 设置在每次重试之前调用的回调。
      Parameters:
      listener - the callback receiving (attempt number, exception) - 接收(尝试次数,异常)的回调
      Returns:
      this builder - 当前构建器
    • onSuccess

      public Retry<T> onSuccess(Consumer<T> listener)
      Set a callback invoked when the task succeeds. 设置任务成功时调用的回调。

      The callback receives the successful result value. Exceptions thrown by the callback are isolated and do not affect the return value.

      回调接收成功的结果值。回调抛出的异常会被隔离,不影响返回值。

      Parameters:
      listener - the success callback - 成功回调
      Returns:
      this builder - 当前构建器
    • onExhausted

      public Retry<T> onExhausted(Consumer<Throwable> listener)
      Set a callback invoked when all retry attempts are exhausted. 设置所有重试尝试用尽时调用的回调。

      The callback receives the last exception. Exceptions thrown by the callback are isolated and do not mask the original failure.

      回调接收最后一个异常。回调抛出的异常会被隔离,不会掩盖原始失败。

      Parameters:
      listener - the exhausted callback - 用尽回调
      Returns:
      this builder - 当前构建器
    • execute

      public T execute()
      Execute the task with retry logic. 使用重试逻辑执行任务。
      Returns:
      the task result - 任务结果
      Throws:
      RuntimeException - if all attempts are exhausted or a non-retryable exception occurs - 如果所有尝试用尽或发生不可重试的异常
    • executeAsync

      public CompletableFuture<T> executeAsync()
      Execute the task asynchronously with retry logic. Returns a CompletableFuture that completes with the result or fails with the last exception. 异步执行带重试逻辑的任务。返回 CompletableFuture,成功时完成结果,失败时携带最后一个异常。

      Uses a virtual thread for the retry loop.

      使用虚拟线程执行重试循环。

      Returns:
      a CompletableFuture with the result - 包含结果的 CompletableFuture
    • executeAsync

      public CompletableFuture<T> executeAsync(Executor executor)
      Execute the task asynchronously with retry logic using the specified executor. 使用指定的执行器异步执行带重试逻辑的任务。
      Parameters:
      executor - the executor to run the retry loop on - 执行重试循环的执行器
      Returns:
      a CompletableFuture with the result - 包含结果的 CompletableFuture
    • execute

      public static <T> T execute(Callable<T> task)
      Execute a task with default retry settings (3 attempts, 100ms fixed delay). 使用默认重试设置执行任务(3次尝试,100毫秒固定延迟)。
      Type Parameters:
      T - the result type - 结果类型
      Parameters:
      task - the task to execute - 要执行的任务
      Returns:
      the task result - 任务结果
    • execute

      public static <T> T execute(Callable<T> task, int maxAttempts)
      Execute a task with the specified max attempts and default backoff. 使用指定的最大尝试次数和默认退避策略执行任务。
      Type Parameters:
      T - the result type - 结果类型
      Parameters:
      task - the task to execute - 要执行的任务
      maxAttempts - the maximum number of attempts - 最大尝试次数
      Returns:
      the task result - 任务结果
    • withConfig

      public static <T> Retry<T> withConfig(Callable<T> task, RetryConfig config)
      Create a Retry instance from a RetryConfig. 从 RetryConfig 创建 Retry 实例。
      Type Parameters:
      T - the result type - 结果类型
      Parameters:
      task - the task to execute - 要执行的任务
      config - the retry configuration - 重试配置
      Returns:
      a configured Retry instance - 已配置的 Retry 实例