Spring的Retryable或RetryTemplate可以使用Retry-After标头进行动态补偿吗? [英] Can Spring's Retryable or RetryTemplate use Retry-After header for dynamic backoff?
问题描述
我可以使Spring的@Retryable或@RetryTemplate使用HTTP 503
服务不可用"响应中的Retry-After
标头中接收的数字作为下一次重试迭代的延迟吗?
Can I make Spring's @Retryable or @RetryTemplate use the number received in a Retry-After
header in an HTTP 503
"Service Unavailable" response as delay for the next retry iteration?
例如:
@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端点来检查准备情况.如果端点可以估计剩余的设置将花费多长时间,则端点发送回带有Retry-After
标头的503
.
Our Java app relies on an external component that takes some minutes to come up. That component provides a REST endpoint to check readiness. The endpoint sends back 503
with a Retry-After
header if it can estimate how long the remaining setup will take.
推荐答案
一种方法是将值存储在静态ThreadLocal
(例如MyHolder.setDelay(...)
)中,并在@Backoff()
中使用delayExpression
检索该值.
One way would be to store the value in a static ThreadLocal
(e.g. MyHolder.setDelay(...)
) and use delayExpression
in the @Backoff()
to retrieve that value.
类似于"T(com.foo.MyHolder).getDelay()"
.
Something like "T(com.foo.MyHolder).getDelay()"
.
您需要使用自定义的BackoffPolicy
将RetryOperationsInterceptor
作为@Bean
连接起来,并在@Retryable.interceptor
属性中引用它.
You would need to wire up a RetryOperationsInterceptor
as a @Bean
with a custom BackoffPolicy
and reference it in the @Retryable.interceptor
property.
这篇关于Spring的Retryable或RetryTemplate可以使用Retry-After标头进行动态补偿吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!