简体   繁体   中英

JAVA-11: java.net.httpClient How to set Retry?

Currently I'm replacing existing org.apache.http.* http client library with JDK-11 's new Http library. There are many exciting new features, however I've not found anything on "how to set RetryRequestHandler in new HTTPClient". Code snippet of previous Apache HttpClient builder :

    ...
    ...
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create()
            .setDefaultRequestConfig(config)
            .setConnectionManager(connectionManager)
    if(retryCount > 0) {
        httpClientBuilder.setRetryHandler(new RetryRequestHandler(retryCount, url));
    }
    if (proxyHost) {
        HttpHost proxy = new HttpHost(proxyHost, proxyPort, "http");
        httpClientBuilder.setProxy(proxy);
    }
    ...
    ...

Here RetryRequestHandler is an extension of DefaultHttpRequestRetryHandler

public class RetryRequestHandler extends DefaultHttpRequestRetryHandler{...} 

There is no option to set retry in java-11's new HttpClient. Is there any workaround to do so?

Spring has broken retry out of Spring Batch into a separate, standalone library that you can use (albeit inside a Spring project). It will allow you to add a retry policy to a method calling the new HTTP client. See docs below:

https://github.com/spring-projects/spring-retry

That's the closest thing I know for this situation. If you want to roll your own, you could also accomplish the same thing with aspects. I think the Spring library is cleaner because you can let the library handle the details of retry. They also have a powerful set of APIs for different retry policies, including exponential backoff, etc.

The java.net.http HttpClient will retry idempotent requests (GET/HEAD) once by default. This is typically useful on HTTP/1.1 long live connections where the server side might arbitrarily decide that the connection has remained idle for too long, and closes it at the same time that the client takes it out of the pool and starts sending a new request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM