Skip to content

org.springframework.http.client.JdkClientHttpRequest cause outer Thread.sleep interrupted #35079

Open
@snovian

Description

@snovian

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    in: webIssues in web modules (web, webmvc, webflux, websocket)status: waiting-for-triageAn issue we've not yet triaged or decided on

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions