Class Retry<T>
java.lang.Object
cloud.opencode.base.core.retry.Retry<T>
- Type Parameters:
T- the result type - 结果类型
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 Summary
Modifier and TypeMethodDescriptionSet a predicate to abort retry immediately when matched.Set the exception type to abort retry immediately.backoff(BackoffStrategy backoff) Set the backoff strategy.Set a fixed delay between retries (convenience forbackoff(BackoffStrategy.fixed(delay))).execute()Execute the task with retry logic.static <T> TExecute a task with default retry settings (3 attempts, 100ms fixed delay).static <T> TExecute a task with the specified max attempts and default backoff.Execute the task asynchronously with retry logic.executeAsync(Executor executor) Execute the task asynchronously with retry logic using the specified executor.exponentialBackoff(Duration initialDelay, double multiplier) Set an exponential backoff strategy (convenience method).maxAttempts(int maxAttempts) Set the maximum number of attempts (including the initial attempt).Set the maximum delay cap.static <T> Retry<T> Create a new Retry builder for the given task.onExhausted(Consumer<Throwable> listener) Set a callback invoked when all retry attempts are exhausted.onRetry(BiConsumer<Integer, Throwable> listener) Set a callback invoked before each retry attempt.Set a callback invoked when the task succeeds.Set the exception type to retry on (convenience forretryOn(type::isInstance)).Set a predicate to determine if a given exception should trigger a retry.retryOnAny(Class<? extends Throwable>... exceptionTypes) Set multiple exception types to retry on.retryOnResult(Predicate<T> predicate) Set a predicate to retry based on the task result.Set a total timeout for all retry attempts combined.static <T> Retry<T> withConfig(Callable<T> task, RetryConfig config) Create a Retry instance from aRetryConfig.
-
Method Details
-
of
-
maxAttempts
-
backoff
Set the backoff strategy. 设置退避策略。- Parameters:
backoff- the backoff strategy - 退避策略- Returns:
- this builder - 当前构建器
-
delay
-
exponentialBackoff
-
maxDelay
-
timeout
-
retryOn
-
retryOn
-
retryOnAny
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
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
-
abortOn
-
onRetry
Set a callback invoked before each retry attempt. 设置在每次重试之前调用的回调。- Parameters:
listener- the callback receiving (attempt number, exception) - 接收(尝试次数,异常)的回调- Returns:
- this builder - 当前构建器
-
onSuccess
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
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
Execute the task with retry logic. 使用重试逻辑执行任务。- Returns:
- the task result - 任务结果
- Throws:
RuntimeException- if all attempts are exhausted or a non-retryable exception occurs - 如果所有尝试用尽或发生不可重试的异常
-
executeAsync
Execute the task asynchronously with retry logic. Returns aCompletableFuturethat 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
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
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
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
Create a Retry instance from aRetryConfig. 从RetryConfig创建 Retry 实例。- Type Parameters:
T- the result type - 结果类型- Parameters:
task- the task to execute - 要执行的任务config- the retry configuration - 重试配置- Returns:
- a configured Retry instance - 已配置的 Retry 实例
-