net.jodah.failsafe.Failsafe Java Examples
The following examples show how to use
net.jodah.failsafe.Failsafe.
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: Issue190Test.java From failsafe with Apache License 2.0 | 6 votes |
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 #2
Source File: Java8Example.java From failsafe with Apache License 2.0 | 6 votes |
@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 #3
Source File: DelayableRetryPolicyTest.java From failsafe with Apache License 2.0 | 6 votes |
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 #4
Source File: LoggingRetryListenerTest.java From riptide with MIT License | 6 votes |
@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 #5
Source File: VertxExample.java From failsafe with Apache License 2.0 | 6 votes |
/** * 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 #6
Source File: CompositeRetryListenerTest.java From riptide with MIT License | 6 votes |
@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 File: Issue36Test.java From failsafe with Apache License 2.0 | 6 votes |
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 #8
Source File: NettyExample.java From failsafe with Apache License 2.0 | 6 votes |
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 #9
Source File: Issue9Test.java From failsafe with Apache License 2.0 | 6 votes |
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 #10
Source File: Issue5Test.java From failsafe with Apache License 2.0 | 6 votes |
/** * 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 #11
Source File: SelectedPortWaitStrategy.java From presto with Apache License 2.0 | 6 votes |
@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 #12
Source File: Issue52Test.java From failsafe with Apache License 2.0 | 6 votes |
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 #13
Source File: FailsafeAdapter.java From samza with Apache License 2.0 | 6 votes |
/** * 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 #14
Source File: Issue55Test.java From failsafe with Apache License 2.0 | 6 votes |
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 File: WebHook.java From bouncr with Eclipse Public License 1.0 | 6 votes |
@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 #16
Source File: Issue131Test.java From failsafe with Apache License 2.0 | 6 votes |
/** * 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 #17
Source File: AwsS3Sender.java From fluency with Apache License 2.0 | 6 votes |
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 #18
Source File: DockerRegistry.java From carnotzet with Apache License 2.0 | 6 votes |
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 #19
Source File: CircuitBreakerManager.java From heimdall with Apache License 2.0 | 6 votes |
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 #20
Source File: CircuitBreakerManager.java From heimdall with Apache License 2.0 | 6 votes |
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 #21
Source File: Issue52Test.java From failsafe with Apache License 2.0 | 5 votes |
@Test(expectedExceptions = CancellationException.class) public void shouldCancelExecutionViaFuture() throws Throwable { ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2); Future<Object> proxyFuture = Failsafe.with(new RetryPolicy<>().withDelay(Duration.ofMillis(10))) .with(scheduler) .getAsync(exec -> { throw new IllegalStateException(); }); assertTrue(proxyFuture.cancel(true)); proxyFuture.get(); // should throw CancellationException per .getAsync() javadoc. }
Example #22
Source File: Neo4jIT.java From baleen with Apache License 2.0 | 5 votes |
private void setPassword(String rootUrl) throws IOException, ClientProtocolException { HttpClient client = createClient("neo4j"); RetryPolicy retryPolicy = new RetryPolicy() .retryOn(NoHttpResponseException.class) .withDelay(1, TimeUnit.SECONDS) .withMaxRetries(3); Failsafe.with(retryPolicy).run(() -> callSetPassword(rootUrl, client)); }
Example #23
Source File: Issue218Test.java From failsafe with Apache License 2.0 | 5 votes |
public void test() { RetryPolicy<Void> retryPolicy = new RetryPolicy<Void>().withMaxAttempts(2); Fallback<Void> fallback = Fallback.VOID; Failsafe.with(fallback, retryPolicy).run(() -> { throw new Exception(); }); }
Example #24
Source File: ExampleRestController.java From problem-spring-web with MIT License | 5 votes |
@RequestMapping("/handler-circuit-breaker-open") public void circuitBreakerOpen() { final CircuitBreaker<Object> breaker = new CircuitBreaker<>(); breaker.open(); Failsafe.with(breaker) .run(() -> {}); }
Example #25
Source File: Issue242Test.java From failsafe with Apache License 2.0 | 5 votes |
public void shouldDelayOnExplicitRetry() throws Throwable { RetryPolicy<String> retryPolicy = new RetryPolicy<String>().handleResult(null) .withDelay(Duration.ofMillis(110)) .withMaxAttempts(3); long startTime = System.currentTimeMillis(); Failsafe.with(retryPolicy).runAsyncExecution(exec -> { if (!exec.complete(null, null)) exec.retry(); }).get(); assertTrue(System.currentTimeMillis() - startTime > 200, "Expected delay between retries"); }
Example #26
Source File: ExampleRestController.java From problem-spring-web with MIT License | 5 votes |
@RequestMapping("/handler-circuit-breaker-open") public void circuitBreakerOpen() { final CircuitBreaker<Object> breaker = new CircuitBreaker<>(); breaker.open(); Failsafe.with(breaker) .run(() -> {}); }
Example #27
Source File: Issue76Test.java From failsafe with Apache License 2.0 | 5 votes |
public void shouldAbortOnSyncError() { AssertionError error = new AssertionError(); try { Failsafe.with(new RetryPolicy<>().abortOn(AssertionError.class)).run(() -> { throw error; }); fail(); } catch (AssertionError e) { assertEquals(e, error); } }
Example #28
Source File: Issue75Test.java From failsafe with Apache License 2.0 | 5 votes |
@Test public void testThatFailSafeIsBrokenWithFallback() throws Exception { CircuitBreaker<Integer> breaker = new CircuitBreaker<Integer>().withFailureThreshold(10, 100).withSuccessThreshold(2).withDelay( Duration.ofMillis(100)); ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); int result = Failsafe.with(Fallback.of(e -> 999), breaker) .with(service) .getStageAsync(() -> CompletableFuture.completedFuture(223)) .get(); Assert.assertEquals(result, 223); }
Example #29
Source File: Issue131Test.java From failsafe with Apache License 2.0 | 5 votes |
/** * Simple synchronous case throwing a {@link NullPointerException} * instead of the expected {@link FailsafeException}. */ @Test(expectedExceptions = FailsafeException.class) public void syncShouldThrowTheUnderlyingIOException() { CircuitBreaker<String> circuitBreaker = new CircuitBreaker<String>().handleResultIf(handleIfEqualsIgnoreCaseFoo); FailsafeExecutor<String> failsafe = Failsafe.with(circuitBreaker); // I expect this getAsync() to throw IOException, not NPE. failsafe.get(() -> { throw new IOException("let's blame it on network error"); }); }
Example #30
Source File: Issue165Test.java From failsafe with Apache License 2.0 | 5 votes |
public void testOfStageAsync() throws Throwable { Fallback<Object> fallback = Fallback.ofStageAsync(e -> CompletableFuture.completedFuture("test")); Object result = Failsafe.with(fallback).getAsync(() -> { throw new IllegalStateException(); }).get(); assertEquals(result, "test"); }