layout | title |
---|---|
default |
OkHttp |
{: .no_toc }
- TOC {:toc}
The Failsafe [OkHttp][okhttp-lib] integration allows Failsafe [policies] to be composed around OkHttp calls.
Add the latest [failsafe][maven] and [failsafe-okhttp][maven-okhttp] dependencies to your project.
Create a [FailsafeCall][FailsafeCall-okhttp] that composes a policy around an OkHttp [Call][okhttp-Call]:
Call call = client.newCall(request);
RetryPolicy<Response> retryPolicy = RetryPolicy.ofDefaults();
FailsafeCall failsafeCall = FailsafeCall.with(retryPolicy).compose(call);
// Execute with retries
Response response = failsafeCall.execute();
Failure handling works just as it does with any Failsafe execution.
Async execution can also be performed for a [FailsafeCall][FailsafeCall-okhttp], which returns a [CompletableFuture]:
CompletableFuture<Response> future = failsafeCall.executeAsync();
Multiple policies can be [composed][policy-composition] around an OkHttp [Call][okhttp-Call]:
FailsafeCall failsafeCall = FailsafeCall.with(fallback)
.compose(retryPolicy)
.compose(circuitBreaker)
.compose(call);
The same statement can also be written as:
FailsafeCall failsafeCall = FailsafeCall.with(fallback, retryPolicy, circuitBreaker).compose(call);
See the [policy-composition] docs for more details.
When a [FailsafeCall][FailsafeCall-okhttp] is cancelled, the underlying OkHttp [Call][okhttp-Call] is also cancelled:
failsafeCall.cancel();
This is also true when cancellation is performed via an async execution's future:
CompletableFuture<Response> future = failsafeCall.executeAsync();
future.cancel(false);
A [FailsafeExecutor] configured with [event listeners][event-listeners] or an [ExecutorService][executorservice-configuration] can be used to create a [FailsafeCall][FailsafeCall-okhttp]:
FailsafeExecutor<Response> failsafe = Failsafe.with(retryPolicy)
.with(executorService)
.onSuccess(e -> log.info("Found user {}", e.getResult()))
.onFailure(e -> log.error("Failed to find user", e.getException()));
FailsafeCall failsafeCall = FailsafeCall.with(failsafe).compose(call);
{% include common-links.html %}