Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use an Exponential Backoff strategy with Apache httpclient?

The docs specify a class of ExponentialBackOffSchedulingStrategy but it doesn't seem to exist in version 4.5.

Also, didn't find anything that explains HOW to use it.

Anyone used something like this before?

like image 472
guyman Avatar asked Oct 31 '22 09:10

guyman


1 Answers

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'll need add another jar to get these classes, like this:

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

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

Then you can wire it up something like this:

 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();
 }
like image 171
jerryb Avatar answered Nov 15 '22 04:11

jerryb