How to use Exponential Backoff strategy with Apache httpclient?

docs points to the ExponentialBackOffSchedulingStrategy class, but it does not seem to exist in version 4.5.

In addition, I did not find anything that explains HOW to use it.

Has anyone used something like this before?

+4
source share
1 answer

If you installed Apache HTTP Client 4.5.x using Maven packages like this (Grails Maven dependency syntax):

compile "org.apache.httpcomponents:httpclient:4.5.1"
compile "org.apache.httpcomponents:httpcore:4.4.3"

You will need to add another jar to get these classes, for example:

compile 'org.apache.httpcomponents:httpclient-cache:4.5.1'

See https://hc.apache.org/httpcomponents-client-4.5.x/download.html

Then you can connect it to the following:

 import org.apache.http.impl.client.*;
 import org.apache.http.impl.client.cache.*;
 import org.apache.http.client.methods.*;

 CloseableHttpClient createClient() {
     CachingHttpClientBuilder hcb = new CachingHttpClientBuilder();
     CacheConfig cc = CacheConfig.DEFAULT;
     ExponentialBackOffSchedulingStrategy ebo = new ExponentialBackOffSchedulingStrategy(cc);
     hcb.setSchedulingStrategy(ebo);
     CloseableHttpClient hc = hcb.build();
     return hc;
 }

 // You'll need to replace the URL below with something that returns a 5xx error
 CloseableHttpClient client = createClient();
 HttpUriRequest request = new HttpGet("http://www.example.com/throwsServerError");
 for (int i=0; i<4; i++) {
     CloseableHttpResponse response =  client.execute(request);
     println new Date().toString() + " " + response.getStatusLine().getStatusCode();
 }
0

Source: https://habr.com/ru/post/1628701/


All Articles