Skip to content

Instantly share code, notes, and snippets.

@Romeh

Romeh/retry.java

Last active Dec 4, 2018
Embed
What would you like to do?
// Given the HelloWorldService returns Hello world
given(helloWorldService.returnHelloWorld())
.willReturn(completedFuture("Hello world"));
final AsyncRetry retryContext = AsyncRetry.of("retryConfig",
// we set the response type to String
RetryConfig.<String>custom()
// max retry attempts
.maxAttempts(3)
// what are the ignore exception to no retry on
.ignoreExceptions(IllegalStateException.class)
// what are the exceptions to try on
.retryExceptions(TimeoutException.class)
// retry if the response contains world
.retryOnResult(s -> s.contains("world"))
// retry backoff strategy, IntervalFunction has many built in interface functions you can check it out
.intervalFunction(IntervalFunction.ofExponentialBackoff())
.build());
// Decorate the invocation of the HelloWorldService
Supplier<CompletionStage<String>> supplier = AsyncRetry.decorateCompletionStage(
retryContext,
scheduler,
() -> helloWorldService.returnHelloWorld());
// When
String result = awaitResult(supplier);
// Then the helloWorldService should be invoked 1 time
BDDMockito.then(helloWorldService).should(Mockito.times(3)).returnHelloWorld();
Assertions.assertEquals(result, "Hello world");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment