Can Spring's Retryable or RetryTemplate use Retry-After header for dynamic backoff?

半城伤御伤魂 提交于 2020-02-05 05:13:24

问题


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?

For example:

@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;
}

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.


回答1:


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.

Something like "T(com.foo.MyHolder).getDelay()".

You would need to wire up a RetryOperationsInterceptor as a @Bean with a custom BackoffPolicy and reference it in the @Retryable.interceptor property.



来源:https://stackoverflow.com/questions/58559733/can-springs-retryable-or-retrytemplate-use-retry-after-header-for-dynamic-backo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!