Skip to content

Instantly share code, notes, and snippets.

@lmolkova
Created July 18, 2021 17:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lmolkova/f34d2dfcb23522b2dc115462f2f76d20 to your computer and use it in GitHub Desktop.
Save lmolkova/f34d2dfcb23522b2dc115462f2f76d20 to your computer and use it in GitHub Desktop.
package com.example.http;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import java.io.IOException;
import io.opentelemetry.api.trace.SpanKind;
import io.opentelemetry.extension.annotations.WithSpan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Application {
private static final Logger LOGGER = LoggerFactory.getLogger(Application.class);
private static final String URL = "http://localhost:8080/send?message=hi there";
public static void main(String ... args) throws IOException {
AppTries(new OkHttpClient());
InterceptorTries(new OkHttpClient());
}
@WithSpan
public static void InterceptorTries(OkHttpClient client) {
client.interceptors().add(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
int tryCount = 0;
while (!response.isSuccessful() && tryCount < 3) {
tryCount++;
// we'd need backoff amd jitter
response = chain.proceed(request);
}
return response;
}
});
String responseBody = null;
try {
responseBody = makeCall(client, URL);
} catch (Exception ex) {
}
LOGGER.info("Received response={}", responseBody);
}
@WithSpan(kind = SpanKind.SERVER)
public static void AppTries(OkHttpClient client) {
String responseBody = null;
for (int tryCount = 0; tryCount < 3; tryCount ++) {
try {
responseBody = makeCall(client, URL);
if (responseBody != null) {
break;
}
} catch (Exception ex) {
}
// we'd need backoff amd jitter
}
LOGGER.info("Received response={}", responseBody);
}
private static String makeCall(OkHttpClient client, String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.isSuccessful() ? String.valueOf(response.body().string()) : null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment