io.github.resilience4j.retry.RetryConfig Java Examples

The following examples show how to use io.github.resilience4j.retry.RetryConfig. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RetryTransformerTest.java    From resilience4j with Apache License 2.0 7 votes vote down vote up
@Test
public void retryOnResultFailAfterMaxAttemptsUsingMaybe() throws InterruptedException {
    RetryConfig config = RetryConfig.<String>custom()
        .retryOnResult("retry"::equals)
        .waitDuration(Duration.ofMillis(50))
        .maxAttempts(3).build();
    Retry retry = Retry.of("testName", config);
    given(helloWorldService.returnHelloWorld())
        .willReturn("retry");

    Maybe.fromCallable(helloWorldService::returnHelloWorld)
        .compose(RetryTransformer.of(retry))
        .test()
        .await()
        .assertValueCount(1)
        .assertValue("retry")
        .assertComplete();

    then(helloWorldService).should(times(3)).returnHelloWorld();
}
 
Example #2
Source File: SupplierRetryTest.java    From resilience4j with Apache License 2.0 7 votes vote down vote up
@Test
public void shouldReturnAfterOneAttemptAndIgnoreException() {
    given(helloWorldService.returnHelloWorld()).willThrow(new HelloWorldException());
    RetryConfig config = RetryConfig.custom()
        .retryOnException(throwable -> API.Match(throwable).of(
            API.Case($(Predicates.instanceOf(HelloWorldException.class)), false),
            API.Case($(), true)))
        .build();
    Retry retry = Retry.of("id", config);
    CheckedFunction0<String> retryableSupplier = Retry
        .decorateCheckedSupplier(retry, helloWorldService::returnHelloWorld);

    Try<String> result = Try.of(retryableSupplier);

    // Because the exception should be rethrown immediately.
    then(helloWorldService).should().returnHelloWorld();
    assertThat(result.isFailure()).isTrue();
    assertThat(result.failed().get()).isInstanceOf(HelloWorldException.class);
    assertThat(sleptTime).isEqualTo(0);
}
 
Example #3
Source File: CompletionStageRetryTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
private void shouldCompleteFutureAfterAttemptsInCaseOfExceptionAtAsyncStage(int noOfAttempts) {
    CompletableFuture<String> failedFuture = new CompletableFuture<>();
    failedFuture.completeExceptionally(new HelloWorldException());
    given(helloWorldService.returnHelloWorld())
        .willReturn(failedFuture);
    Retry retryContext = Retry.of(
        "id",
        RetryConfig
            .custom()
            .maxAttempts(noOfAttempts)
            .build());
    Supplier<CompletionStage<String>> supplier = Retry.decorateCompletionStage(
        retryContext,
        scheduler,
        () -> helloWorldService.returnHelloWorld());

    Try<String> resultTry = Try.of(() -> awaitResult(supplier.get()));

    then(helloWorldService).should(times(noOfAttempts)).returnHelloWorld();
    assertThat(resultTry.isFailure()).isTrue();
    assertThat(resultTry.getCause().getCause()).isInstanceOf(HelloWorldException.class);
}
 
Example #4
Source File: RunnableRetryTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnAfterOneAttemptAndIgnoreException() {
    willThrow(new HelloWorldException()).given(helloWorldService).sayHelloWorld();
    RetryConfig config = RetryConfig.custom()
        .retryOnException(throwable -> Match(throwable).of(
            Case($(Predicates.instanceOf(HelloWorldException.class)), false),
            Case($(), true)))
        .build();
    Retry retry = Retry.of("id", config);
    CheckedRunnable retryableRunnable = Retry
        .decorateCheckedRunnable(retry, helloWorldService::sayHelloWorld);

    Try<Void> result = Try.run(retryableRunnable);

    // because the exception should be rethrown immediately
    then(helloWorldService).should().sayHelloWorld();
    assertThat(result.isFailure()).isTrue();
    assertThat(result.failed().get()).isInstanceOf(HelloWorldException.class);
    assertThat(sleptTime).isEqualTo(0);
}
 
Example #5
Source File: RetryTransformerTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void retryOnResultFailAfterMaxAttemptsUsingObservable() throws InterruptedException {
    RetryConfig config = RetryConfig.<String>custom()
        .retryOnResult("retry"::equals)
        .waitDuration(Duration.ofMillis(50))
        .maxAttempts(3).build();
    Retry retry = Retry.of("testName", config);
    given(helloWorldService.returnHelloWorld())
        .willReturn("retry");

    Observable.fromCallable(helloWorldService::returnHelloWorld)
        .compose(RetryTransformer.of(retry))
        .test()
        .await()
        .assertValueCount(1)
        .assertValue("retry")
        .assertComplete();

    then(helloWorldService).should(times(3)).returnHelloWorld();
}
 
Example #6
Source File: PublicAccessAutoFix.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
   * Gets the instance details for ec 2.
   *
   * @param clientMap the client map
   * @param resourceId the resource id
   * @return the instance details for ec 2
   * @throws Exception the exception
   */
  public static Instance getInstanceDetailsForEc2(Map<String,Object> clientMap,String resourceId) throws Exception {
  	AmazonEC2 ec2Client = (AmazonEC2) clientMap.get("client");
  	DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest();
describeInstancesRequest.setInstanceIds(Arrays.asList(resourceId));


RetryConfig config = RetryConfig.custom().maxAttempts(MAX_ATTEMPTS).waitDuration(Duration.ofSeconds(WAIT_INTERVAL)).build();
RetryRegistry registry = RetryRegistry.of(config);

Retry retry = registry.retry(describeInstancesRequest.toString());
 		
Function<Integer, Instance> decorated
  =  Retry.decorateFunction(retry, (Integer s) -> {
	  DescribeInstancesResult  describeInstancesResult =  ec2Client.describeInstances(describeInstancesRequest);
	  List<Reservation> reservations = describeInstancesResult.getReservations();
		Reservation reservation = reservations.get(0);
		List<Instance> instances = reservation.getInstances();
		return instances.get(0);
    });
return decorated.apply(1);
	
  }
 
Example #7
Source File: EventPublisherTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldIgnoreError() {
    willThrow(new HelloWorldException()).willDoNothing().given(helloWorldService)
        .sayHelloWorld();
    RetryConfig config = RetryConfig.custom()
        .retryOnException(t -> t instanceof IOException)
        .maxAttempts(3).build();
    Retry retry = Retry.of("id", config);
    TestSubscriber<RetryEvent.Type> testSubscriber = toFlowable(retry.getEventPublisher())
        .map(RetryEvent::getEventType)
        .test();
    CheckedRunnable retryableRunnable = Retry
        .decorateCheckedRunnable(retry, helloWorldService::sayHelloWorld);

    Try<Void> result = Try.run(retryableRunnable);

    then(helloWorldService).should().sayHelloWorld();
    assertThat(result.isFailure()).isTrue();
    assertThat(sleptTime).isEqualTo(0);
    testSubscriber.assertValueCount(1).assertValues(RetryEvent.Type.IGNORED_ERROR);
}
 
Example #8
Source File: RetryTransformerTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void doNotRetryFromPredicateUsingSingle() {
    RetryConfig config = RetryConfig.custom()
        .retryOnException(t -> t instanceof IOException)
        .waitDuration(Duration.ofMillis(50))
        .maxAttempts(3).build();
    Retry retry = Retry.of("testName", config);
    given(helloWorldService.returnHelloWorld())
        .willThrow(new HelloWorldException());
    Single.fromCallable(helloWorldService::returnHelloWorld)
        .compose(RetryTransformer.of(retry))
        .test()
        .assertError(HelloWorldException.class)
        .assertNotComplete()
        .assertSubscribed();

    then(helloWorldService).should().returnHelloWorld();
    Retry.Metrics metrics = retry.getMetrics();

    assertThat(metrics.getNumberOfFailedCallsWithoutRetryAttempt()).isEqualTo(1);
    assertThat(metrics.getNumberOfFailedCallsWithRetryAttempt()).isEqualTo(0);
}
 
Example #9
Source File: EventPublisherTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnAfterThreeAttempts() {
    willThrow(new HelloWorldException()).given(helloWorldService).sayHelloWorld();
    Retry retry = Retry.ofDefaults("id");
    TestSubscriber<RetryEvent.Type> testSubscriber = toFlowable(retry.getEventPublisher())
        .map(RetryEvent::getEventType)
        .test();
    CheckedRunnable retryableRunnable = Retry
        .decorateCheckedRunnable(retry, helloWorldService::sayHelloWorld);

    Try<Void> result = Try.run(retryableRunnable);

    then(helloWorldService).should(times(3)).sayHelloWorld();
    assertThat(result.isFailure()).isTrue();
    assertThat(result.failed().get()).isInstanceOf(HelloWorldException.class);
    assertThat(sleptTime).isEqualTo(RetryConfig.DEFAULT_WAIT_DURATION * 2);
    testSubscriber.assertValueCount(3)
        .assertValues(RetryEvent.Type.RETRY, RetryEvent.Type.RETRY, RetryEvent.Type.ERROR);
}
 
Example #10
Source File: RetryConfigurationPropertiesTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testExponentialRandomBackoffConfig() {
    //Given
    RetryConfigurationProperties.InstanceProperties instanceProperties1 = new RetryConfigurationProperties.InstanceProperties();
    instanceProperties1.setMaxRetryAttempts(3);
    instanceProperties1.setWaitDuration(Duration.ofMillis(1000));
    instanceProperties1.setEnableExponentialBackoff(true);
    instanceProperties1.setEnableRandomizedWait(true);
    instanceProperties1.setRandomizedWaitFactor(0.5D);
    instanceProperties1.setExponentialBackoffMultiplier(2.0D);

    RetryConfigurationProperties retryConfigurationProperties = new RetryConfigurationProperties();
    retryConfigurationProperties.getInstances().put("backend1", instanceProperties1);

    //Then
    final RetryConfig retry1 = retryConfigurationProperties
        .createRetryConfig("backend1", compositeRetryCustomizer());
    assertThat(retry1).isNotNull();
    assertThat(retry1.getIntervalFunction().apply(1)).isBetween(500L, 1500L);
    assertThat(retry1.getIntervalFunction().apply(2)).isBetween(1000L, 3000L);

}
 
Example #11
Source File: RetryOperatorTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void returnOnErrorUsingMono() {
    RetryConfig config = retryConfig();
    Retry retry = Retry.of("testName", config);
    RetryOperator<String> retryOperator = RetryOperator.of(retry);
    given(helloWorldService.returnHelloWorld())
        .willThrow(new HelloWorldException());

    StepVerifier.create(Mono.fromCallable(helloWorldService::returnHelloWorld)
        .transformDeferred(retryOperator))
        .expectSubscription()
        .expectError(HelloWorldException.class)
        .verify(Duration.ofSeconds(1));

    StepVerifier.create(Mono.fromCallable(helloWorldService::returnHelloWorld)
        .transformDeferred(retryOperator))
        .expectSubscription()
        .expectError(HelloWorldException.class)
        .verify(Duration.ofSeconds(1));

    then(helloWorldService).should(times(6)).returnHelloWorld();
    Retry.Metrics metrics = retry.getMetrics();
    assertThat(metrics.getNumberOfFailedCallsWithRetryAttempt()).isEqualTo(2);
    assertThat(metrics.getNumberOfFailedCallsWithoutRetryAttempt()).isEqualTo(0);
}
 
Example #12
Source File: TaggedRetryMetricsPublisherTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReplaceMetrics() {
    Collection<FunctionCounter> counters = meterRegistry.get(DEFAULT_RETRY_CALLS).functionCounters();
    Optional<FunctionCounter> successfulWithoutRetry = MetricsTestHelper.findMeterByKindAndNameTags(counters,
        "successful_without_retry", retry.getName());
    assertThat(successfulWithoutRetry).isPresent();
    assertThat(successfulWithoutRetry.get().count())
        .isEqualTo(retry.getMetrics().getNumberOfSuccessfulCallsWithoutRetryAttempt());

    Retry newRetry = Retry.of(retry.getName(), RetryConfig.custom().maxAttempts(1).build());

    retryRegistry.replace(retry.getName(), newRetry);

    counters = meterRegistry.get(DEFAULT_RETRY_CALLS).functionCounters();
    successfulWithoutRetry = MetricsTestHelper
        .findMeterByKindAndNameTags(counters, "successful_without_retry",
        newRetry.getName());
    assertThat(successfulWithoutRetry).isPresent();
    assertThat(successfulWithoutRetry.get().count())
        .isEqualTo(newRetry.getMetrics().getNumberOfSuccessfulCallsWithoutRetryAttempt());
}
 
Example #13
Source File: RetryTransformerTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void doNotRetryFromPredicateUsingSingle() {
    RetryConfig config = RetryConfig.custom()
        .retryOnException(t -> t instanceof IOException)
        .waitDuration(Duration.ofMillis(50))
        .maxAttempts(3).build();
    Retry retry = Retry.of("testName", config);
    given(helloWorldService.returnHelloWorld())
        .willThrow(new HelloWorldException());
    Single.fromCallable(helloWorldService::returnHelloWorld)
        .compose(RetryTransformer.of(retry))
        .test()
        .assertError(HelloWorldException.class)
        .assertNotComplete();

    then(helloWorldService).should().returnHelloWorld();
    Retry.Metrics metrics = retry.getMetrics();

    assertThat(metrics.getNumberOfFailedCallsWithoutRetryAttempt()).isEqualTo(1);
    assertThat(metrics.getNumberOfFailedCallsWithRetryAttempt()).isEqualTo(0);
}
 
Example #14
Source File: TaggedRetryMetricsTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReplaceMetrics() {
    Collection<FunctionCounter> counters = meterRegistry.get(DEFAULT_RETRY_CALLS)
        .functionCounters();
    Optional<FunctionCounter> successfulWithoutRetry = findMeterByKindAndNameTags(counters,
        "successful_without_retry", retry.getName());
    assertThat(successfulWithoutRetry).isPresent();
    assertThat(successfulWithoutRetry.get().count())
        .isEqualTo(retry.getMetrics().getNumberOfSuccessfulCallsWithoutRetryAttempt());

    Retry newRetry = Retry.of(retry.getName(), RetryConfig.custom().maxAttempts(1).build());

    retryRegistry.replace(retry.getName(), newRetry);

    counters = meterRegistry.get(DEFAULT_RETRY_CALLS).functionCounters();
    successfulWithoutRetry = findMeterByKindAndNameTags(counters, "successful_without_retry",
        newRetry.getName());
    assertThat(successfulWithoutRetry).isPresent();
    assertThat(successfulWithoutRetry.get().count())
        .isEqualTo(newRetry.getMetrics().getNumberOfSuccessfulCallsWithoutRetryAttempt());
}
 
Example #15
Source File: RetryTransformerTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void doNotRetryFromPredicateUsingCompletable() {
    RetryConfig config = RetryConfig.custom()
        .retryOnException(t -> t instanceof IOException)
        .waitDuration(Duration.ofMillis(50))
        .maxAttempts(3).build();
    Retry retry = Retry.of("testName", config);
    doThrow(new HelloWorldException()).when(helloWorldService).sayHelloWorld();

    Completable.fromRunnable(helloWorldService::sayHelloWorld)
        .compose(RetryTransformer.of(retry))
        .test()
        .assertError(HelloWorldException.class)
        .assertNotComplete();

    then(helloWorldService).should().sayHelloWorld();
    Retry.Metrics metrics = retry.getMetrics();
    assertThat(metrics.getNumberOfFailedCallsWithoutRetryAttempt()).isEqualTo(1);
    assertThat(metrics.getNumberOfFailedCallsWithRetryAttempt()).isEqualTo(0);
}
 
Example #16
Source File: RetryTransformerTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test(expected = StackOverflowError.class)
public void shouldNotRetryUsingSingleStackOverFlow() {
    RetryConfig config = retryConfig();
    Retry retry = Retry.of("testName", config);
    given(helloWorldService.returnHelloWorld())
        .willThrow(new StackOverflowError("BAM!"));

    Single.fromCallable(helloWorldService::returnHelloWorld)
        .compose(RetryTransformer.of(retry))
        .test();

    then(helloWorldService).should().returnHelloWorld();
    Retry.Metrics metrics = retry.getMetrics();
    assertThat(metrics.getNumberOfFailedCallsWithoutRetryAttempt()).isEqualTo(0);
    assertThat(metrics.getNumberOfFailedCallsWithRetryAttempt()).isEqualTo(0);
}
 
Example #17
Source File: RunnableRetryTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldTakeIntoAccountBackoffFunction() {
    willThrow(new HelloWorldException()).given(helloWorldService).sayHelloWorld();
    RetryConfig config = RetryConfig
        .custom()
        .intervalFunction(IntervalFunction.of(Duration.ofMillis(500), x -> x * x))
        .build();
    Retry retry = Retry.of("id", config);
    CheckedRunnable retryableRunnable = Retry
        .decorateCheckedRunnable(retry, helloWorldService::sayHelloWorld);

    Try.run(retryableRunnable);

    then(helloWorldService).should(times(3)).sayHelloWorld();
    assertThat(sleptTime).isEqualTo(
        RetryConfig.DEFAULT_WAIT_DURATION +
            RetryConfig.DEFAULT_WAIT_DURATION * RetryConfig.DEFAULT_WAIT_DURATION);
}
 
Example #18
Source File: CompletionStageRetryTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
private void shouldCompleteFutureAfterAttemptsInCaseOfRetyOnResultAtAsyncStage(int noOfAttempts,
    String retryResponse) {
    given(helloWorldService.returnHelloWorld())
        .willReturn(completedFuture("Hello world"));
    Retry retryContext = Retry.of(
        "id",
        RetryConfig
            .<String>custom()
            .maxAttempts(noOfAttempts)
            .retryOnResult(s -> s.contains(retryResponse))
            .build());
    Supplier<CompletionStage<String>> supplier = Retry.decorateCompletionStage(
        retryContext,
        scheduler,
        () -> helloWorldService.returnHelloWorld());

    Try<String> resultTry = Try.of(() -> awaitResult(supplier.get()));

    then(helloWorldService).should(times(noOfAttempts)).returnHelloWorld();
    assertThat(resultTry.isSuccess()).isTrue();
}
 
Example #19
Source File: Resilience4jUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenRetryIsUsed_thenItWorksAsExpected() {
    RetryConfig config = RetryConfig.custom().maxAttempts(2).build();
    RetryRegistry registry = RetryRegistry.of(config);
    Retry retry = registry.retry("my");
    Function<Integer, Void> decorated = Retry.decorateFunction(retry, (Integer s) -> {
        service.process(s);
        return null;
    });

    when(service.process(anyInt())).thenThrow(new RuntimeException());
    try {
        decorated.apply(1);
        fail("Expected an exception to be thrown if all retries failed");
    } catch (Exception e) {
        verify(service, times(2)).process(any(Integer.class));
    }
}
 
Example #20
Source File: SupplierRetryTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
private void shouldCompleteFutureAfterAttemptsInCaseOfRetyOnResultAtAsyncStage(int noOfAttempts,
    String retryResponse) {
    given(helloWorldServiceAsync.returnHelloWorld())
        .willReturn(completedFuture("Hello world"));
    Retry retryContext = Retry.of(
        "id",
        RetryConfig
            .<String>custom()
            .maxAttempts(noOfAttempts)
            .retryOnResult(s -> s.contains(retryResponse))
            .build());
    Supplier<CompletionStage<String>> supplier = Retry.decorateCompletionStage(
        retryContext,
        scheduler,
        () -> helloWorldServiceAsync.returnHelloWorld());

    Try<String> resultTry = Try.of(() -> awaitResult(supplier.get()));

    then(helloWorldServiceAsync).should(times(noOfAttempts)).returnHelloWorld();
    assertThat(resultTry.isSuccess()).isTrue();
}
 
Example #21
Source File: SupplierRetryTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldTakeIntoAccountBackoffFunction() {
    given(helloWorldService.returnHelloWorld()).willThrow(new HelloWorldException());
    RetryConfig config = RetryConfig.custom()
        .intervalFunction(IntervalFunction.ofExponentialBackoff(500, 2.0))
        .build();
    Retry retry = Retry.of("id", config);
    CheckedFunction0<String> retryableSupplier = Retry
        .decorateCheckedSupplier(retry, helloWorldService::returnHelloWorld);

    Try.of(retryableSupplier);

    then(helloWorldService).should(times(3)).returnHelloWorld();
    assertThat(sleptTime).isEqualTo(
        RetryConfig.DEFAULT_WAIT_DURATION +
            RetryConfig.DEFAULT_WAIT_DURATION * 2);
}
 
Example #22
Source File: RetryTransformerTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void retryOnResultUsingSingle() throws InterruptedException {
    RetryConfig config = RetryConfig.<String>custom()
        .retryOnResult("retry"::equals)
        .waitDuration(Duration.ofMillis(50))
        .maxAttempts(3).build();
    Retry retry = Retry.of("testName", config);
    given(helloWorldService.returnHelloWorld())
        .willReturn("retry")
        .willReturn("success");

    Single.fromCallable(helloWorldService::returnHelloWorld)
        .compose(RetryTransformer.of(retry))
        .test()
        .await()
        .assertValueCount(1)
        .assertValue("success")
        .assertComplete();

    then(helloWorldService).should(times(2)).returnHelloWorld();
    Retry.Metrics metrics = retry.getMetrics();
    assertThat(metrics.getNumberOfFailedCallsWithoutRetryAttempt()).isEqualTo(0);
    assertThat(metrics.getNumberOfSuccessfulCallsWithRetryAttempt()).isEqualTo(1);
}
 
Example #23
Source File: RetryOperatorTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void retryOnResultFailAfterMaxAttemptsUsingMono() {
    RetryConfig config = RetryConfig.<String>custom()
        .retryOnResult("retry"::equals)
        .waitDuration(Duration.ofMillis(10))
        .maxAttempts(3).build();
    Retry retry = Retry.of("testName", config);
    given(helloWorldService.returnHelloWorld())
        .willReturn("retry");

    StepVerifier.create(Mono.fromCallable(helloWorldService::returnHelloWorld)
        .transformDeferred(RetryOperator.of(retry)))
        .expectSubscription()
        .expectNextCount(1)
        .expectComplete()
        .verify(Duration.ofSeconds(1));

    then(helloWorldService).should(times(3)).returnHelloWorld();
}
 
Example #24
Source File: RetryTransformerTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void retryOnResultUsingObservable() throws InterruptedException {
    RetryConfig config = RetryConfig.<String>custom()
        .retryOnResult("retry"::equals)
        .waitDuration(Duration.ofMillis(50))
        .maxAttempts(3).build();
    Retry retry = Retry.of("testName", config);
    given(helloWorldService.returnHelloWorld())
        .willReturn("retry")
        .willReturn("success");

    Observable.fromCallable(helloWorldService::returnHelloWorld)
        .compose(RetryTransformer.of(retry))
        .test()
        .await()
        .assertValueCount(1)
        .assertValue("success")
        .assertComplete();

    then(helloWorldService).should(times(2)).returnHelloWorld();
    Retry.Metrics metrics = retry.getMetrics();
    assertThat(metrics.getNumberOfFailedCallsWithoutRetryAttempt()).isEqualTo(0);
    assertThat(metrics.getNumberOfSuccessfulCallsWithRetryAttempt()).isEqualTo(1);
}
 
Example #25
Source File: RetryConfigCustomizer.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
/**
 * A convenient method to create RetryConfigCustomizer using {@link Consumer}
 *
 * @param instanceName the name of the instance
 * @param consumer     delegate call to Consumer when  {@link RetryConfigCustomizer#customize(RetryConfig.Builder)}
 *                     is called
 * @return Customizer instance
 */
static RetryConfigCustomizer of(@NonNull String instanceName,
    @NonNull Consumer<RetryConfig.Builder> consumer) {
    return new RetryConfigCustomizer() {

        @Override
        public void customize(RetryConfig.Builder builder) {
            consumer.accept(builder);
        }

        @Override
        public String name() {
            return instanceName;
        }
    };
}
 
Example #26
Source File: RetryTransformerTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void doNotRetryFromPredicateUsingFlowable() {
    RetryConfig config = RetryConfig.custom()
        .retryOnException(t -> t instanceof IOException)
        .waitDuration(Duration.ofMillis(50))
        .maxAttempts(3).build();
    Retry retry = Retry.of("testName", config);
    given(helloWorldService.returnHelloWorld())
        .willThrow(new HelloWorldException());

    Flowable.fromCallable(helloWorldService::returnHelloWorld)
        .compose(RetryTransformer.of(retry))
        .test()
        .assertError(HelloWorldException.class)
        .assertNotComplete();

    then(helloWorldService).should().returnHelloWorld();
    Retry.Metrics metrics = retry.getMetrics();
    assertThat(metrics.getNumberOfFailedCallsWithoutRetryAttempt()).isEqualTo(1);
    assertThat(metrics.getNumberOfFailedCallsWithRetryAttempt()).isEqualTo(0);
}
 
Example #27
Source File: RetryTransformerTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void retryOnResultUsingMaybe() throws InterruptedException {
    RetryConfig config = RetryConfig.<String>custom()
        .retryOnResult("retry"::equals)
        .waitDuration(Duration.ofMillis(50))
        .maxAttempts(3).build();
    Retry retry = Retry.of("testName", config);
    given(helloWorldService.returnHelloWorld())
        .willReturn("retry")
        .willReturn("success");
    Maybe.fromCallable(helloWorldService::returnHelloWorld)
        .compose(RetryTransformer.of(retry))
        .test()
        .await()
        .assertValueCount(1)
        .assertValue("success")
        .assertComplete();

    then(helloWorldService).should(times(2)).returnHelloWorld();

    Retry.Metrics metrics = retry.getMetrics();
    assertThat(metrics.getNumberOfFailedCallsWithoutRetryAttempt()).isEqualTo(0);
    assertThat(metrics.getNumberOfSuccessfulCallsWithRetryAttempt()).isEqualTo(1);
}
 
Example #28
Source File: RetryTransformerTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void doNotRetryFromPredicateUsingMaybe() {
    RetryConfig config = RetryConfig.custom()
        .retryOnException(t -> t instanceof IOException)
        .waitDuration(Duration.ofMillis(50))
        .maxAttempts(3).build();
    Retry retry = Retry.of("testName", config);
    given(helloWorldService.returnHelloWorld())
        .willThrow(new HelloWorldException());

    Maybe.fromCallable(helloWorldService::returnHelloWorld)
        .compose(RetryTransformer.of(retry))
        .test()
        .assertError(HelloWorldException.class)
        .assertNotComplete();

    then(helloWorldService).should().returnHelloWorld();

    Retry.Metrics metrics = retry.getMetrics();
    assertThat(metrics.getNumberOfFailedCallsWithoutRetryAttempt()).isEqualTo(1);
    assertThat(metrics.getNumberOfFailedCallsWithRetryAttempt()).isEqualTo(0);
}
 
Example #29
Source File: RetryTransformerTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void retryOnResultUsingMaybe() throws InterruptedException {
    RetryConfig config = RetryConfig.<String>custom()
        .retryOnResult("retry"::equals)
        .waitDuration(Duration.ofMillis(50))
        .maxAttempts(3).build();
    Retry retry = Retry.of("testName", config);
    given(helloWorldService.returnHelloWorld())
        .willReturn("retry")
        .willReturn("success");
    Maybe.fromCallable(helloWorldService::returnHelloWorld)
        .compose(RetryTransformer.of(retry))
        .test()
        .await()
        .assertValueCount(1)
        .assertValue("success")
        .assertComplete()
        .assertSubscribed();

    then(helloWorldService).should(times(2)).returnHelloWorld();

    Retry.Metrics metrics = retry.getMetrics();
    assertThat(metrics.getNumberOfFailedCallsWithoutRetryAttempt()).isEqualTo(0);
    assertThat(metrics.getNumberOfSuccessfulCallsWithRetryAttempt()).isEqualTo(1);
}
 
Example #30
Source File: RetryOperatorTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotRetryWhenItThrowErrorMono() {
    RetryConfig config = retryConfig();
    Retry retry = Retry.of("testName", config);
    RetryOperator<String> retryOperator = RetryOperator.of(retry);
    given(helloWorldService.returnHelloWorld())
        .willThrow(new Error("BAM!"));

    StepVerifier.create(Mono.fromCallable(helloWorldService::returnHelloWorld)
        .transformDeferred(retryOperator))
        .expectSubscription()
        .expectError(Error.class)
        .verify(Duration.ofSeconds(1));

    then(helloWorldService).should().returnHelloWorld();
    Retry.Metrics metrics = retry.getMetrics();
    assertThat(metrics.getNumberOfFailedCallsWithRetryAttempt()).isEqualTo(0);
    assertThat(metrics.getNumberOfFailedCallsWithoutRetryAttempt()).isEqualTo(0);
}