Java Code Examples for net.jodah.failsafe.Failsafe

The following examples show how to use net.jodah.failsafe.Failsafe. These examples are extracted from open source projects. 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 Project: presto   Source File: SelectedPortWaitStrategy.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void waitUntilReady()
{
    Callable<Boolean> internalCheck = new InternalCommandPortListeningCheck(waitStrategyTarget, exposedPorts);

    Set<Integer> externalPorts = exposedPorts.stream()
            .map(waitStrategyTarget::getMappedPort)
            .collect(toImmutableSet());
    Callable<Boolean> externalCheck = new ExternalPortListeningCheck(waitStrategyTarget, externalPorts);

    Failsafe.with(new RetryPolicy<>()
            .withMaxDuration(startupTimeout)
            .withMaxAttempts(Integer.MAX_VALUE) // limited by MaxDuration
            .abortOn(e -> getExitCode().isPresent()))
            .run(() -> {
                if (!getRateLimiter().getWhenReady(() -> internalCheck.call() && externalCheck.call())) {
                    // We say "timed out" immediately. Failsafe will propagate this only when timeout reached.
                    throw new ContainerLaunchException(format(
                            "Timed out waiting for container port to open (%s ports: %s should be listening)",
                            waitStrategyTarget.getContainerIpAddress(),
                            exposedPorts));
                }
            });
}
 
Example 2
Source Project: heimdall   Source File: CircuitBreakerManager.java    License: Apache License 2.0 6 votes vote down vote up
public <T> T failsafe(Callable<T> callable, Long operationId, String operationPath) {
	CircuitBreakerHolder circuitBreakerHolder = getCircuitHolder(operationId, circuits);
	CircuitBreaker circuitBreaker = circuitBreakerHolder.getCircuitBreaker();
	
	if (circuitBreaker.isOpen()) {
		return Failsafe.with(circuitBreaker)
				.withFallback(() ->  {
					String body = logAndCreateBody("CircuitBreaker ENABLED | Operation: {0}, Exception: {1}",
							operationPath,
                               circuitBreakerHolder.getMessage());

					RequestContext context = RequestContext.getCurrentContext();
					context.setSendZuulResponse(false);
					context.setResponseStatusCode(HttpStatus.SERVICE_UNAVAILABLE.value());
					context.setResponseBody(body);
					context.addZuulResponseHeader(ConstantsContext.CIRCUIT_BREAKER_ENABLED, "enabled");
					context.getResponse().setContentType(MediaType.APPLICATION_JSON_VALUE);
				})
				.get(callable);
	}

	return Failsafe.with(circuitBreaker)
			.onFailure((ignored, throwable) -> circuitBreakerHolder.setThrowable(throwable))
			.get(callable);
}
 
Example 3
Source Project: heimdall   Source File: CircuitBreakerManager.java    License: Apache License 2.0 6 votes vote down vote up
public <T> T failsafe(Callable<T> callable, String url) {
	CircuitBreakerHolder circuitBreakerHolder = getCircuitHolder(url, middlewareCircuits);
	CircuitBreaker circuitBreaker = circuitBreakerHolder.getCircuitBreaker();

	if (circuitBreaker.isOpen()) {
		return Failsafe.with(circuitBreaker)
				.withFallback(() -> {

					String body = logAndCreateBody("CircuitBreaker ENABLED | URL: {0}, Exception: {1}",
							url,
                               circuitBreakerHolder.getMessage());

					return ResponseEntity
							.status(HttpStatus.SERVICE_UNAVAILABLE.value())
							.header(ConstantsContext.CIRCUIT_BREAKER_ENABLED, "enabled")
							.body(body);

				}).get(callable);
	}

	return Failsafe.with(circuitBreaker)
			.onFailure((ignored, throwable) -> circuitBreakerHolder.setThrowable(throwable))
			.get(callable);
}
 
Example 4
Source Project: carnotzet   Source File: DockerRegistry.java    License: Apache License 2.0 6 votes vote down vote up
private String downloadImageManifestAsString(String digest, ImageRef imageRef) {
	WebTarget registry = getRegistryWebTarget(imageRef);
	WebTarget url = registry.path("v2/{name}/blobs/{reference}")
			.resolveTemplate("name", imageRef.getImageName(), false)
			.resolveTemplate("reference", digest, false);
	log.info("Downloading image manifest from {} ...", url.getUri().toString());

	RetryPolicy<Object> retryPolicy = new RetryPolicy<>()
			.handle(WebApplicationException.class)
			.withDelay(Duration.ofSeconds(Integer.parseInt(System.getProperty(CARNOTZET_MANIFEST_RETRY_DELAY_SECONDS, "1"))))
			.withMaxRetries(Integer.parseInt(System.getProperty(CARNOTZET_MANIFEST_DOWNLOAD_RETRIES, "0")))
			.onRetry((o) -> log.info("Download attempt failed: {} : Retrying... ", o.getLastFailure().toString()))
			.onFailure((o) -> {
				log.error("Download failed: {} ", o.getFailure().toString());
				throw new IllegalStateException(o.getFailure());
			});
	String value = Failsafe.with(retryPolicy).get(() ->
			url.request("application/vnd.docker.container.image.v1+json").get(String.class)
	);

	log.info("Image manifest downloaded");
	return value;
}
 
Example 5
Source Project: bouncr   Source File: WebHook.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void run(T object) {
    RetryPolicy retryPolicy = method.equalsIgnoreCase("get") ? idempotent : notIdempotent;
    Failsafe.with(retryPolicy)
            .with(executor)
            .onSuccess(response -> {

            })
            .get(() -> {
                RequestBody body = RequestBody.create(JSON, mapper.writeValueAsString(object));
                Request.Builder requestBuilder;
                requestBuilder = new Request.Builder()
                        .url(url)
                        .header("content-type", "application/json")
                        .method(method, body);
                if (headers != null) {
                    headers.forEach(requestBuilder::addHeader);
                }
                return client.newCall(requestBuilder.build()).execute();
            });
}
 
Example 6
Source Project: riptide   Source File: CompositeRetryListenerTest.java    License: MIT License 6 votes vote down vote up
@Test
void shouldPropagateRetryToEveryListener() {
    final AtomicBoolean success = new AtomicBoolean(false);

    final RequestArguments arguments = RequestArguments.create();
    final IllegalStateException exception = new IllegalStateException();

    Failsafe.with(new RetryPolicy<ClientHttpResponse>()
            .withMaxRetries(3)
            .onRetry(new RetryRequestPolicy.RetryListenerAdapter(unit, arguments)))
            .run(() -> {
                if (!success.getAndSet(true)) {
                    throw exception;
                }
            });

    verify(first).onRetry(eq(arguments), argThat(hasFeature(ExecutionAttemptedEvent::getLastResult, nullValue())));
    verify(first).onRetry(eq(arguments), argThat(hasFeature(ExecutionAttemptedEvent::getLastFailure, notNullValue())));
    verify(second).onRetry(eq(arguments), argThat(hasFeature(ExecutionAttemptedEvent::getLastResult, nullValue())));
    verify(second).onRetry(eq(arguments), argThat(hasFeature(ExecutionAttemptedEvent::getLastFailure, notNullValue())));
}
 
Example 7
Source Project: riptide   Source File: LoggingRetryListenerTest.java    License: MIT License 6 votes vote down vote up
@Test
void shouldNotLogResults() {
    final AtomicBoolean success = new AtomicBoolean(false);

    final RequestArguments arguments = RequestArguments.create();

    Failsafe.with(new RetryPolicy<ClientHttpResponse>()
            .withMaxRetries(3)
            .handleResultIf(Objects::isNull)
            .onRetry(new RetryListenerAdapter(unit, arguments)))
            .get(() -> {
                if (!success.getAndSet(true)) {
                    return null;
                }

                return mock(ClientHttpResponse.class);
            });

    verifyNoMoreInteractions(logger);
}
 
Example 8
Source Project: failsafe   Source File: DelayableRetryPolicyTest.java    License: Apache License 2.0 6 votes vote down vote up
public void shouldDelayOnMatchingFailureType() {
  AtomicInteger delays = new AtomicInteger(0);
  RetryPolicy<Integer> retryPolicy = new RetryPolicy<Integer>()
      .handle(UncheckedExpectedException.class)
      .withMaxRetries(4)
      .withDelayOn((r, f, c) -> {
        delays.incrementAndGet(); // side-effect for test purposes
        return Duration.ofNanos(1);
      }, DelayException.class);

  AtomicInteger attempts = new AtomicInteger(0);
  int result = Failsafe.with(Fallback.of(123), retryPolicy).get(() -> {
    int i = attempts.getAndIncrement();
    switch (i) {
      case 0:
      case 2:
        throw new DelayException();
      default:
        throw new UncheckedExpectedException();
    }
  });

  assertEquals(result, 123, "Fallback should be used");
  assertEquals(attempts.get(), 5, "Expecting five attempts (1 + 4 retries)");
  assertEquals(delays.get(), 2, "Expecting two dynamic delays matching DelayException failure");
}
 
Example 9
Source Project: failsafe   Source File: Java8Example.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unused")
public static void main(String... args) {
  ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
  RetryPolicy<Object> retryPolicy = new RetryPolicy<>();

  // Create a retryable functional interface
  Function<String, String> bar = value -> Failsafe.with(retryPolicy).get(() -> value + "bar");

  // Create a retryable Stream operation
  Failsafe.with(retryPolicy).get(() -> Stream.of("foo")
      .map(value -> Failsafe.with(retryPolicy).get(() -> value + "bar"))
      .collect(Collectors.toList()));

  // Create a individual retryable Stream operation
  Stream.of("foo").map(value -> Failsafe.with(retryPolicy).get(() -> value + "bar")).forEach(System.out::println);

  // Create a retryable CompletableFuture
  Failsafe.with(retryPolicy).with(executor).getStageAsync(() -> CompletableFuture.supplyAsync(() -> "foo")
      .thenApplyAsync(value -> value + "bar")
      .thenAccept(System.out::println));

  // Create an individual retryable CompletableFuture stages
  CompletableFuture.supplyAsync(() -> Failsafe.with(retryPolicy).get(() -> "foo"))
      .thenApplyAsync(value -> Failsafe.with(retryPolicy).get(() -> value + "bar"))
      .thenAccept(System.out::println);
}
 
Example 10
Source Project: failsafe   Source File: VertxExample.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * A Vert.x sender and retryable receiver example.
 */
public static void main(String... args) throws Throwable {
  // Receiver that fails 3 times then succeeds
  AtomicInteger failures = new AtomicInteger();
  vertx.eventBus().consumer("ping-address", message -> {
    if (failures.getAndIncrement() < 3)
      message.fail(1, "Failed");
    else {
      message.reply("pong!");
    }
  });

  // Retryable sender
  Failsafe.with(retryPolicy.copy().withDelay(Duration.ofSeconds(1)))
      .with(scheduler)
      .runAsyncExecution(execution -> vertx.eventBus().send("ping-address", "ping!", reply -> {
        if (reply.succeeded())
          System.out.println("Received reply " + reply.result().body());
        else if (!execution.retryOn(reply.cause()))
          System.out.println("Execution and retries failed");
      }));

  Thread.sleep(5000);
}
 
Example 11
Source Project: failsafe   Source File: NettyExample.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String... args) throws Throwable {
  EventLoopGroup group = new NioEventLoopGroup();
  Bootstrap bootstrap = createBootstrap(group);
  RetryPolicy<Object> retryPolicy = new RetryPolicy<>().withDelay(Duration.ofSeconds(1));

  Failsafe.with(retryPolicy).with(group).runAsyncExecution(
      execution -> bootstrap.connect(HOST, PORT).addListener((ChannelFutureListener) channelFuture -> {
        if (channelFuture.isSuccess()) {
          System.out.println("Connected!");
          try {
            channelFuture.sync();
            channelFuture.channel().closeFuture().sync();
          } catch (Exception ignore) {
            group.shutdownGracefully();
          }
        } else if (!execution.retryOn(channelFuture.cause()))
          System.out.println("Connection attempts failed");
      }));

  Thread.sleep(5000);
}
 
Example 12
Source Project: failsafe   Source File: Issue9Test.java    License: Apache License 2.0 6 votes vote down vote up
public void test() throws Throwable {
  // Given - Fail twice then succeed
  AtomicInteger retryCounter = new AtomicInteger();
  Service service = mock(Service.class);
  when(service.connect()).thenThrow(failures(2, new IllegalStateException())).thenReturn(true);
  ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
  Waiter waiter = new Waiter();

  // When
  AtomicInteger successCounter = new AtomicInteger();
  Future<Boolean> future = Failsafe.with(new RetryPolicy<Boolean>().withMaxRetries(2)
      .onRetry(e -> retryCounter.incrementAndGet()))
      .with(executor)
      .onSuccess(p -> {
        successCounter.incrementAndGet();
        waiter.resume();
      })
      .getAsync(service::connect);

  // Then
  waiter.await(1000);
  verify(service, times(3)).connect();
  assertTrue(future.get());
  assertEquals(retryCounter.get(), 2);
  assertEquals(successCounter.get(), 1);
}
 
Example 13
Source Project: failsafe   Source File: Issue190Test.java    License: Apache License 2.0 6 votes vote down vote up
public void test() throws Throwable {
  RetryPolicy<Object> policy = new RetryPolicy<>().withMaxRetries(5);
  AtomicInteger failureEvents = new AtomicInteger();
  AtomicInteger successEvents = new AtomicInteger();
  Waiter waiter = new Waiter();

  Failsafe.with(policy).onFailure(e -> {
    failureEvents.incrementAndGet();
    waiter.resume();
  }).onSuccess(e -> {
    successEvents.incrementAndGet();
    waiter.resume();
  }).getAsyncExecution(execution -> Testing.futureResult(executor, true).whenComplete((result, failure) -> {
    execution.complete(result);
  })).get();

  waiter.await(1000);
  Assert.assertEquals(failureEvents.get(), 0);
  Assert.assertEquals(successEvents.get(), 1);
}
 
Example 14
Source Project: failsafe   Source File: Issue55Test.java    License: Apache License 2.0 6 votes vote down vote up
public void shouldOnlyFallbackOnFailure() throws Throwable {
  ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

  AtomicInteger counter = new AtomicInteger();
  Failsafe.with(Fallback.of(counter::incrementAndGet), new RetryPolicy<>()).with(executor).getAsync(() -> null);

  Thread.sleep(100);
  assertEquals(counter.get(), 0);

  Failsafe.with(Fallback.of(counter::incrementAndGet), new RetryPolicy<>().withMaxRetries(1))
      .with(executor)
      .runAsync(() -> {
        throw new RuntimeException();
      });

  Thread.sleep(100);
  assertEquals(counter.get(), 1);
}
 
Example 15
Source Project: failsafe   Source File: Issue131Test.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * More alarming async case where the Future is not even completed
 * since Failsafe does not recover from the {@link NullPointerException} thrown by the predicate.
 */
public void asyncShouldCompleteTheFuture() throws Throwable {
  CircuitBreaker<String> circuitBreaker = new CircuitBreaker<String>().handleResultIf(handleIfEqualsIgnoreCaseFoo);
  FailsafeExecutor<String> failsafe = Failsafe.with(circuitBreaker).with(Executors.newSingleThreadScheduledExecutor());

  Waiter waiter = new Waiter();

  failsafe
    .getStageAsync(() -> {
      CompletableFuture<String> future = new CompletableFuture<>();
      future.completeExceptionally(new IOException("let's blame it on network error"));
      return future;
    })
    .whenComplete((s, t) -> waiter.resume()); // Never invoked!

  waiter.await(1000);
}
 
Example 16
Source Project: failsafe   Source File: Issue5Test.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Asserts that a failure is handled as expected by a listener registered via whenFailure.
 */
public void test() throws Throwable {
  Waiter waiter = new Waiter();
  RetryPolicy<Object> retryPolicy = new RetryPolicy<>().withDelay(Duration.ofMillis(100))
      .withMaxDuration(Duration.ofSeconds(2))
      .withMaxRetries(3)
      .handleResult(null);

  ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
  Failsafe.with(retryPolicy).with(executor).onFailure(e -> {
    waiter.assertNull(e.getResult());
    waiter.assertNull(e.getFailure());
    waiter.resume();
  }).getAsync(() -> null);

  waiter.await(1000);
}
 
Example 17
Source Project: failsafe   Source File: Issue36Test.java    License: Apache License 2.0 6 votes vote down vote up
public void test() {
  try {
    Failsafe.with(retryPolicy
        .onFailedAttempt(e -> failedAttempts.incrementAndGet())
        .onRetry(e -> retries.incrementAndGet()))
        .get(() -> {
          calls.incrementAndGet();
          throw new Exception();
        });
    fail();
  } catch (Exception expected) {
  }

  // Then
  assertCounters();
}
 
Example 18
Source Project: failsafe   Source File: Issue52Test.java    License: Apache License 2.0 6 votes vote down vote up
public void shouldCancelExecutionViaCompletableFuture() throws Throwable {
  ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
  AtomicInteger counter = new AtomicInteger();
  CompletableFuture<String> proxyFuture = Failsafe.with(new RetryPolicy<>().withDelay(Duration.ofMillis(10)))
      .with(scheduler)
      .getStageAsync(exec -> {
        Thread.sleep(100);
        counter.incrementAndGet();
        CompletableFuture<String> result = new CompletableFuture<>();
        result.completeExceptionally(new RuntimeException());
        return result;
      });

  assertTrue(proxyFuture.cancel(true));
  int count = counter.get();

  assertTrue(proxyFuture.isCancelled());
  Asserts.assertThrows(proxyFuture::get, CancellationException.class);

  // Assert that execution has actually stopped
  Thread.sleep(20);
  assertEquals(count, counter.get());
}
 
Example 19
Source Project: samza   Source File: FailsafeAdapter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Obtain an async failsafe retryer instance with the specified policy, metrics, and executor service.
 * @param retryPolicy retry policy
 * @param metrics retry metrics
 * @param retryExec executor service for scheduling async retries
 * @return {@link net.jodah.failsafe.AsyncFailsafe} instance
 */
static AsyncFailsafe<?> failsafe(RetryPolicy retryPolicy, RetryMetrics metrics, ScheduledExecutorService retryExec) {
  long startMs = System.currentTimeMillis();
  return Failsafe.with(retryPolicy).with(retryExec)
      .onRetry(e -> metrics.retryCount.inc())
      .onRetriesExceeded(e -> {
        metrics.retryTimer.update(System.currentTimeMillis() - startMs);
        metrics.permFailureCount.inc();
      })
      .onSuccess((e, ctx) -> {
        if (ctx.getExecutions() > 1) {
          metrics.retryTimer.update(System.currentTimeMillis() - startMs);
        } else {
          metrics.successCount.inc();
        }
      });
}
 
Example 20
Source Project: fluency   Source File: AwsS3Sender.java    License: Apache License 2.0 6 votes vote down vote up
public void send(String bucket, String key, ByteBuffer dataBuffer)
        throws IOException
{
    File file = File.createTempFile("tmp-fluency-", ".tmp");
    try {
        try (InputStream in = new ByteBufferBackedInputStream(dataBuffer);
                OutputStream fout = Files.newOutputStream(file.toPath(), StandardOpenOption.WRITE);
                OutputStream out = config.isCompressionEnabled() ? new GZIPOutputStream(fout) : fout) {
            copyStreams(in, out);
        }

        Failsafe.with(retryPolicy).run(() -> uploadData(bucket, key, file));
    }
    finally {
        if (!file.delete()) {
            LOG.warn("Failed to delete a temp file: {}", file.getAbsolutePath());
        }
    }
}
 
Example 21
Source Project: jlibra   Source File: Wait.java    License: Apache License 2.0 5 votes vote down vote up
public static void until(WaitCondition waitCondition) {
    RetryPolicy<Boolean> retryPolicy = new RetryPolicy<Boolean>()
            .onFailedAttempt(
                    e -> logger.info("Condition was not met. Retrying..", e.getLastFailure()))
            .withDelay(Duration.ofMillis(1000))
            .withMaxRetries(5)
            .withMaxDuration(Duration.ofSeconds(10))
            .handleResult(Boolean.FALSE);

    Failsafe.with(retryPolicy).get(() -> waitCondition.isFulfilled());
}
 
Example 22
Source Project: Patterdale   Source File: RetriableDataSource.java    License: Apache License 2.0 5 votes vote down vote up
public static HikariDataSource retriableDataSource(Callable<HikariDataSource> dataSource,
                                                   RuntimeParameters runtimeParams,
                                                   DatabaseDefinition databaseDefinition,
                                                   Logger logger) {
    RetryPolicy retryPolicy = new RetryPolicy()
            .retryOn(HikariPool.PoolInitializationException.class)
            .withDelay(runtimeParams.connectionRetryDelayInSeconds(), SECONDS)
            .withMaxRetries(runtimeParams.maxConnectionRetries());

    return Failsafe.with(retryPolicy)
            .onRetry((result, failure, context) -> logRetry(runtimeParams, databaseDefinition, logger))
            .onFailedAttempt((result, failure, context) -> logFailedAttempt(databaseDefinition, logger))
            .onRetriesExceeded(throwable -> logRetriesExceeded(databaseDefinition, logger))
            .get(dataSource);
}
 
Example 23
Source Project: StubbornJava   Source File: Retry.java    License: MIT License 5 votes vote down vote up
public static String retryUntilSuccessfulWithBackoff(Callable<Response> callable) {
    try (Response response = Failsafe.with(HTTP_200_RETRY).get(callable)) {
        return response.body().string();
    } catch (IOException e) {
        throw Exceptions.sneaky(e);
    }
}
 
Example 24
Source Project: StubbornJava   Source File: CircuitBreakerHandler.java    License: MIT License 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    Failsafe.with(circuitBreaker)
            .withFallback(() -> failureHandler.handleRequest(exchange))
            // We need to call get here instead of execute so we can return the
            // mutated exchange to run checks on it
            .get(() -> {
                delegate.handleRequest(exchange);
                return exchange;
            });
}
 
Example 25
Source Project: StubbornJava   Source File: Retry.java    License: MIT License 5 votes vote down vote up
public static String retryUntilSuccessfulWithBackoff(Callable<Response> callable) {
    try (Response response = Failsafe.with(HTTP_200_RETRY).get(callable)) {
        return response.body().string();
    } catch (IOException e) {
        throw Exceptions.sneaky(e);
    }
}
 
Example 26
Source Project: StubbornJava   Source File: CircuitBreakerHandler.java    License: MIT License 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    Failsafe.with(circuitBreaker)
            .withFallback(() -> failureHandler.handleRequest(exchange))
            // We need to call get here instead of execute so we can return the
            // mutated exchange to run checks on it
            .get(() -> {
                delegate.handleRequest(exchange);
                return exchange;
            });
}
 
Example 27
Source Project: jetcd   Source File: ClientConnectionManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * execute the task and retry it in case of failure.
 *
 * @param  task          a function that returns a new SourceFuture.
 * @param  resultConvert a function that converts Type S to Type T.
 * @param  doRetry       a function that determines the retry condition base on SourceFuture error.
 * @param  <S>           Source type
 * @param  <T>           Converted Type.
 * @return               a CompletableFuture with type T.
 */
public <S, T> CompletableFuture<T> execute(Callable<ListenableFuture<S>> task, Function<S, T> resultConvert,
    Predicate<Throwable> doRetry) {

    RetryPolicy<S> retryPolicy = new RetryPolicy<S>().handleIf(doRetry)
        .onRetriesExceeded(e -> newEtcdException(ErrorCode.ABORTED, "maximum number of auto retries reached"))
        .withBackoff(builder.retryDelay(), builder.retryMaxDelay(), builder.retryChronoUnit());

    if (builder.retryMaxDuration() != null) {
        retryPolicy = retryPolicy.withMaxDuration(Duration.parse(builder.retryMaxDuration()));
    }

    return Failsafe.with(retryPolicy).with(executorService).getAsync(() -> task.call().get()).thenApply(resultConvert);
}
 
Example 28
Source Project: riptide   Source File: FailsafePlugin.java    License: MIT License 5 votes vote down vote up
@Override
public RequestExecution aroundAsync(final RequestExecution execution) {
    return arguments -> {
        final List<Policy<ClientHttpResponse>> policies = select(arguments);

        if (policies.isEmpty()) {
            return execution.execute(arguments);
        }

        return Failsafe.with(select(arguments))
                .getStageAsync(decorator.decorate(context -> execution
                        .execute(withAttempts(arguments, context.getAttemptCount()))));
    };
}
 
Example 29
Source Project: riptide   Source File: LoggingRetryListenerTest.java    License: MIT License 5 votes vote down vote up
@Test
void shouldLogFailure() {
    final AtomicBoolean success = new AtomicBoolean(false);

    final RequestArguments arguments = RequestArguments.create();
    final IllegalStateException exception = new IllegalStateException();

    Failsafe.with(new RetryPolicy<ClientHttpResponse>()
            .withMaxRetries(3)
            .onRetry(new RetryListenerAdapter(unit, arguments)))
            .run(() -> {
                if (!success.getAndSet(true)) {
                    throw exception;
                }
            });

    verify(logger).warn(any(), eq(exception));
}
 
Example 30
Source Project: failsafe   Source File: AsyncExample.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String... args) throws Throwable {
  Failsafe.with(retryPolicy)
      .with(executor)
      .getAsyncExecution(execution -> service.connect().whenComplete((result, failure) -> {
        if (execution.complete(result, failure))
          System.out.println("Success");
        else if (!execution.retry())
          System.out.println("Connection attempts failed");
      }));

  Thread.sleep(3000);
}