我可以让Spring的@Retryable或@RetryTemplate使用HTTP Retry-After“服务不可用”响应中的503标头中接收的数字作为下一次重试迭代的延迟吗?

例如:

@Retryable(maxAttempts = 42,
           backoff = @Backoff(delay = 1000),
           value = NotYetReady.class)
public boolean isExternalComponentReadyToUse() throws NotYetReady {
    ResponseEntity<String> response = callRestEndpointToCheckReadiness();
    if (!response.getStatus().is2xxSuccessful()) {
        int retryAfterInSeconds = response.getHeaders().get("Retry-After");
        // tell @Retryable to run next attempt after retryAfterInSeconds?
        throw new NotYetReady();
    }
    return true;
}


我们的Java应用程序依赖一个外部组件,该组件需要花费几分钟的时间。该组件提供了一个REST端点来检查准备情况。如果端点可以估计剩余的设置将花费多长时间,则端点发送带有503标头的Retry-After

最佳答案

一种方法是将值存储在静态ThreadLocal(例如MyHolder.setDelay(...))中,并在delayExpression中使用@Backoff()检索该值。

类似于"T(com.foo.MyHolder).getDelay()"

您需要使用自定义的RetryOperationsInterceptor@Bean作为BackoffPolicy连接起来,并在@Retryable.interceptor属性中引用它。

10-06 02:26