Open
Description
JdkClientHttpRequest may cause outer Thread.sleep failed
JDK: 21
Spring-Web: 6.2.7
@Configuration
public class RestClientConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(RestClientConfig.class);
@Bean
public RestClient restClient() {
var factory = new JdkClientHttpRequestFactory();
factory.setReadTimeout(120000);
//factory.setConnectTimeout(6000);
return RestClient.builder()
.requestInterceptor(new RetryInterceptor(3))
.requestFactory(factory)
.build();
}
static class RetryInterceptor implements ClientHttpRequestInterceptor {
private final int maxRetries;
public RetryInterceptor(int maxRetries) {
this.maxRetries = maxRetries;
}
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws java.io.IOException {
int attempts = 0;
while (true) {
try {
if(attempts != 0) {
try {
var sleepTime = new Random().nextInt(3, 15);
LOGGER.info("sleeping for {} seconds", sleepTime);
TimeUnit.SECONDS.sleep(sleepTime);
} catch (InterruptedException ex) {
LOGGER.info("", ex);
}
}
LOGGER.info("try {} times for request: {}", attempts + 1, request.getURI());
return execution.execute(request, body);
} catch (Exception e) {
LOGGER.error("", e);
if (++attempts > maxRetries) {
throw e;
}
}
}
}
}
}
if TimeUnit.SECONDS.sleep(sleepTime);
executed, InterruptedException occurred immediately