Java Code Examples for org.eclipse.microprofile.faulttolerance.Asynchronous

The following examples show how to use org.eclipse.microprofile.faulttolerance.Asynchronous. 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
/**
 * Service will retry a method returning a chained, running sequentially, CompletionStage configured to completeExceptionally twice.
 *
 * @return a {@link CompletionStage}
 */
@Asynchronous
@Retry(maxRetries = 3)
public CompletionStage<String> serviceD() {
    countInvocationsServD++;

    if (countInvocationsServD < 3) {
        // fail 2 first invocations
        return CompletableFuture.supplyAsync(doTask(null), executor)
            .thenCompose(s -> CompletableFuture.supplyAsync(doTask("Simulated error"), executor));
    }
    else {
        return CompletableFuture.supplyAsync(doTask(null), executor)
            .thenCompose(s -> CompletableFuture.supplyAsync(doTask(null), executor));
    }
}
 
Example 2
void registerInterceptorBindings(@Observes BeforeBeanDiscovery bbd, BeanManager bm) {
    LOGGER.info("MicroProfile: Fault Tolerance activated");
    bbd.addInterceptorBinding(new FTInterceptorBindingAnnotatedType<>(bm.createAnnotatedType(CircuitBreaker.class)));
    bbd.addInterceptorBinding(new FTInterceptorBindingAnnotatedType<>(bm.createAnnotatedType(Retry.class)));
    bbd.addInterceptorBinding(new FTInterceptorBindingAnnotatedType<>(bm.createAnnotatedType(Timeout.class)));
    bbd.addInterceptorBinding(new FTInterceptorBindingAnnotatedType<>(bm.createAnnotatedType(Asynchronous.class)));
    bbd.addInterceptorBinding(new FTInterceptorBindingAnnotatedType<>(bm.createAnnotatedType(Fallback.class)));
    bbd.addInterceptorBinding(new FTInterceptorBindingAnnotatedType<>(bm.createAnnotatedType(Bulkhead.class)));

    // It seems that fraction deployment module cannot be picked up as a CDI bean archive - see also SWARM-1725
    bbd.addAnnotatedType(bm.createAnnotatedType(FaultToleranceInterceptor.class),
            FaultToleranceInterceptor.class.getName());
    bbd.addAnnotatedType(bm.createAnnotatedType(DefaultFallbackHandlerProvider.class),
            DefaultFallbackHandlerProvider.class.getName());
    bbd.addAnnotatedType(bm.createAnnotatedType(ExecutorProvider.class),
            ExecutorProvider.class.getName());
    bbd.addAnnotatedType(bm.createAnnotatedType(DefaultFaultToleranceOperationProvider.class),
            DefaultFaultToleranceOperationProvider.class.getName());
    bbd.addAnnotatedType(bm.createAnnotatedType(MetricsCollectorFactory.class), MetricsCollectorFactory.class.getName());
    bbd.addAnnotatedType(bm.createAnnotatedType(StrategyCache.class), StrategyCache.class.getName());
}
 
Example 3
/**
 * Service will retry a method returning a parallel execution of 2 CompletionStages. One of them configured to
 * always fail.
 *
 * @return a {@link CompletionStage}
 */
@Asynchronous
@Retry(maxRetries = 3)
public CompletionStage<String> serviceF() {
    countInvocationsServF++;

    if (countInvocationsServF < 3) {
        // fail 2 first invocations
        return CompletableFuture.supplyAsync(doTask(null), executor)
            .thenCombine(CompletableFuture.supplyAsync(doTask("Simulated error"), executor),
                (s, s2) -> s + " then " + s2);
    }
    else {
        return CompletableFuture.supplyAsync(doTask(null), executor)
            .thenCombine(CompletableFuture.supplyAsync(doTask(null), executor),
                (s, s2) -> s + " then " + s2);
    }


}
 
Example 4
@Deployment
public static WebArchive deploy() {
   Asset config = new DisableConfigAsset()
           .enable(Retry.class)
           .enable(CircuitBreaker.class)
           .enable(Timeout.class)
           .enable(Asynchronous.class)
           .enable(Fallback.class)
           .enable(Bulkhead.class)
           .disableGlobally();

    JavaArchive testJar = ShrinkWrap
        .create(JavaArchive.class, "ftDisableGlobalEnableClass.jar")
        .addClasses(DisableAnnotationClient.class)
        .addPackage(Packages.UTILS)
        .addAsManifestResource(config, "microprofile-config.properties")
        .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
        .as(JavaArchive.class);

    WebArchive war = ShrinkWrap
        .create(WebArchive.class, "ftDisableGlobalEnableClass.war")
        .addAsLibrary(testJar);
    return war;
}
 
Example 5
@Deployment
public static WebArchive deploy() {
   Asset config = new DisableConfigAsset()
           .enable(DisableAnnotationClient.class, "failAndRetryOnce", Retry.class)
           .enable(DisableAnnotationClient.class, "failWithCircuitBreaker", CircuitBreaker.class)
           .enable(DisableAnnotationClient.class, "failWithTimeout", Timeout.class)
           .enable(DisableAnnotationClient.class, "asyncWaitThenReturn", Asynchronous.class)
           .enable(DisableAnnotationClient.class, "failRetryOnceThenFallback", Fallback.class)
           .enable(DisableAnnotationClient.class, "waitWithBulkhead", Bulkhead.class)
           .disableGlobally();

    JavaArchive testJar = ShrinkWrap
        .create(JavaArchive.class, "ftDisableGloballyEnableMethod.jar")
        .addClasses(DisableAnnotationClient.class)
        .addPackage(Packages.UTILS)
        .addAsManifestResource(config, "microprofile-config.properties")
        .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
        .as(JavaArchive.class);

    WebArchive war = ShrinkWrap
        .create(WebArchive.class, "ftDisableGloballyEnableMethod.war")
        .addAsLibrary(testJar);
    return war;
}
 
Example 6
@Deployment
public static WebArchive deploy() {
    Asset config = new DisableConfigAsset()
            .disable(DisableAnnotationClient.class, "failAndRetryOnce", Retry.class)
            .disable(DisableAnnotationClient.class, "failRetryOnceThenFallback", Fallback.class)
            .disable(DisableAnnotationClient.class, "failWithCircuitBreaker", CircuitBreaker.class)
            .disable(DisableAnnotationClient.class, "failWithTimeout", Timeout.class)
            .disable(DisableAnnotationClient.class, "asyncWaitThenReturn", Asynchronous.class)
            .disable(DisableAnnotationClient.class, "waitWithBulkhead", Bulkhead.class);
    
    JavaArchive testJar = ShrinkWrap
        .create(JavaArchive.class, "ftDisableMethods.jar")
        .addClasses(DisableAnnotationClient.class)
        .addPackage(Packages.UTILS)
        .addAsManifestResource(config, "microprofile-config.properties")
        .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
        .as(JavaArchive.class);

    WebArchive war = ShrinkWrap
        .create(WebArchive.class, "ftDisableMethods.war")
        .addAsLibrary(testJar);
    return war;
}
 
Example 7
@Deployment
public static WebArchive deploy() {
   Asset config = new DisableConfigAsset()
           .enable(DisableAnnotationClient.class, Retry.class)
           .enable(DisableAnnotationClient.class, CircuitBreaker.class)
           .enable(DisableAnnotationClient.class, Timeout.class)
           .enable(DisableAnnotationClient.class, Asynchronous.class)
           .enable(DisableAnnotationClient.class, Fallback.class)
           .enable(DisableAnnotationClient.class, Bulkhead.class)
           .disableGlobally();

    JavaArchive testJar = ShrinkWrap
        .create(JavaArchive.class, "ftDisableGlobalEnableClass.jar")
        .addClasses(DisableAnnotationClient.class)
        .addPackage(Packages.UTILS)
        .addAsManifestResource(config, "microprofile-config.properties")
        .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
        .as(JavaArchive.class);

    WebArchive war = ShrinkWrap
        .create(WebArchive.class, "ftDisableGlobalEnableClass.war")
        .addAsLibrary(testJar);
    return war;
}
 
Example 8
@Deployment
public static WebArchive deploy() {
    
    Asset config = new DisableConfigAsset()
            .disable(Retry.class)
            .disable(CircuitBreaker.class)
            .disable(Timeout.class)
            .disable(Asynchronous.class)
            .disable(Fallback.class)
            .disable(Bulkhead.class);
    
    JavaArchive testJar = ShrinkWrap
        .create(JavaArchive.class, "ftDisableGlobally.jar")
        .addClasses(DisableAnnotationClient.class)
        .addPackage(Packages.UTILS)
        .addAsManifestResource(config, "microprofile-config.properties")
        .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
        .as(JavaArchive.class);

    WebArchive war = ShrinkWrap
        .create(WebArchive.class, "ftDisableGlobally.war")
        .addAsLibrary(testJar);
    return war;
}
 
Example 9
@Deployment
public static WebArchive deploy() {
   Asset config = new DisableConfigAsset()
           .disable(DisableAnnotationClient.class, Retry.class)
           .disable(DisableAnnotationClient.class, CircuitBreaker.class)
           .disable(DisableAnnotationClient.class, Timeout.class)
           .disable(DisableAnnotationClient.class, Asynchronous.class)
           .disable(DisableAnnotationClient.class, Fallback.class)
           .disable(DisableAnnotationClient.class, Bulkhead.class);
    
    JavaArchive testJar = ShrinkWrap
        .create(JavaArchive.class, "ftDisableClass.jar")
        .addClasses(DisableAnnotationClient.class)
        .addPackage(Packages.UTILS)
        .addAsManifestResource(config, "microprofile-config.properties")
        .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
        .as(JavaArchive.class);

    WebArchive war = ShrinkWrap
        .create(WebArchive.class, "ftDisableClass.war")
        .addAsLibrary(testJar);
    return war;
}
 
Example 10
/**
 * Configured to always time out and Retry until CircuitBreaker is triggered on 4th call. Runs asynchronously.
 */
@CircuitBreaker(successThreshold = 2, requestVolumeThreshold = 4, failureRatio = 0.75, delay = 50000)
@Retry(retryOn = {TestException.class, TimeoutException.class}, maxRetries = 7, maxDuration = 20000)
@Timeout(100) // Scaled via config
@Asynchronous
public Future<Connection> serviceC() {
    Connection conn = null;
    counterForInvokingServiceC++;

    try {
        Thread.sleep(TCKConfig.getConfig().getTimeoutInMillis(5000));
        throw new RuntimeException("Timeout did not interrupt");
    } 
    catch (InterruptedException e) {
        //expected
    }
    return CompletableFuture.completedFuture(conn);
}
 
Example 11
/**
 * Service will retry a method returning a CompletionStage and configured to completeExceptionally twice.
 *
 * @return a {@link CompletionStage}
 */
@Asynchronous
@Retry(maxRetries = 3)
public CompletionStage<String> serviceC() {
    countInvocationsServC++;

    CompletableFuture<String> future = new CompletableFuture<>();

    if (countInvocationsServC < 3) {
        // fail 2 first invocations
        future.completeExceptionally(new IOException("Simulated error"));
    }
    else {
        future.complete("Success");
    }
    return future;
}
 
Example 12
/**
 * serviceA is a slow running service that will take 5 seconds in normal operation. Here it is
 * configured to time out after 2 seconds.
 * @return the result as a Future
 * @throws InterruptedException the interrupted exception
 */
@Timeout(2000)
@Asynchronous
public Future<Connection> serviceA() throws InterruptedException {

    Connection conn = new Connection() {
        {
            Thread.sleep(TCKConfig.getConfig().getTimeoutInMillis(5000));
        }
        
        @Override
        public String getData() {
            return "serviceA DATA";
        }
    };

    return CompletableFuture.completedFuture(conn);
}
 
Example 13
/**
 * serviceB is a fast running service that will take 0.5 seconds in normal operation. That is considerably quicker than
 * its configured time out of 2 seconds.
 * @return the result as a Future
 * @throws InterruptedException the interrupted exception
 */
@Timeout(2000)
@Asynchronous
public Future<Connection> serviceB() throws InterruptedException {

    Connection conn = new Connection() {
        {
            Thread.sleep(TCKConfig.getConfig().getTimeoutInMillis(500));
        }
        
        @Override
        public String getData() {
            return "serviceB DATA";
        }
    };

    return CompletableFuture.completedFuture(conn);
}
 
Example 14
@Asynchronous
@Bulkhead(value = 5, waitingTaskQueue = 10)
private Future writeSomeLogging(String item) {
        LOGGER.info("New Customer order at: "+new java.util.Date());
        LOGGER.info("Item: {}", item);
        return CompletableFuture.completedFuture("ok");
}
 
Example 15
Source Project: smallrye-fault-tolerance   Source File: Service.java    License: Apache License 2.0 5 votes vote down vote up
@Fallback(fallbackMethod = "fallback")
@Timeout(value = 1L)
@Retry(delay = 1L, maxRetries = 2)
@Asynchronous
public CompletionStage<String> hello() {
    tracer.buildSpan("hello").start().finish();
    throw new RuntimeException();
}
 
Example 16
Source Project: smallrye-fault-tolerance   Source File: Service.java    License: Apache License 2.0 5 votes vote down vote up
@Fallback(fallbackMethod = "asyncFallback")
@Timeout(value = 1500L)
@Retry(delay = 100L, maxRetries = 2)
@Asynchronous
public CompletionStage<String> asyncFoo() {
    mockTracer.buildSpan("asyncFoo").start().finish();
    throw new RuntimeException();
}
 
Example 17
Source Project: smallrye-fault-tolerance   Source File: MyMicroservice.java    License: Apache License 2.0 5 votes vote down vote up
@Asynchronous
public Future<String> sayHelloAsync() {
    try {
        Thread.sleep(100);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
    return CompletableFuture.completedFuture(HELLO);
}
 
Example 18
Source Project: smallrye-fault-tolerance   Source File: MyMicroservice.java    License: Apache License 2.0 5 votes vote down vote up
@Asynchronous
@Timeout(200)
@Fallback(FutureStringFallbackHandler.class)
public Future<String> sayHelloAsyncTimeoutFallback() {
    try {
        Thread.sleep(500);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
    return CompletableFuture.completedFuture(HELLO);
}
 
Example 19
Source Project: smallrye-fault-tolerance   Source File: HelloService.java    License: Apache License 2.0 5 votes vote down vote up
@Asynchronous
@Fallback(fallbackMethod = "fallbackCompletionStage")
public CompletionStage<String> helloCompletionStageFailingAsync(int counter) throws IOException {
    CompletableFuture<String> result = new CompletableFuture<>();
    result.completeExceptionally(new IOException());
    return result;
}
 
Example 20
Source Project: smallrye-fault-tolerance   Source File: HelloService.java    License: Apache License 2.0 5 votes vote down vote up
@Asynchronous
@Fallback(fallbackMethod = "fallbackFuture")
public Future<String> helloFutureFailingAsync(int counter) throws IOException {
    CompletableFuture<String> result = new CompletableFuture<>();
    result.completeExceptionally(new IOException());
    return result;
}
 
Example 21
/**
 * Service will retry a method returning a parallel execution of 2 CompletionStages. One of them configured to
 * fail twice.
 *
 * @return a {@link CompletionStage}
 */
@Asynchronous
@Retry(maxRetries = 2)
public CompletionStage<String> serviceG() {
    countInvocationsServG++;
    // always fail
    return CompletableFuture.supplyAsync(doTask(null), executor)
        .thenCombine(CompletableFuture.supplyAsync(doTask("Simulated error"), executor),
            (s, s2) -> s + " then " + s2);

}
 
Example 22
@Asynchronous
@Fallback(fallbackMethod = "fallback")
public Future<String> hello(Result result) throws IOException {
    switch (result) {
        case FAILURE:
            throw new IOException("Simulated IO error");
        case COMPLETE_EXCEPTIONALLY:
            CompletableFuture<String> future = new CompletableFuture<>();
            future.completeExceptionally(new IOException("Simulated IO error"));
            return future;
        default:
            return completedFuture("Hello");
    }
}
 
Example 23
@Asynchronous
@Fallback(fallbackMethod = "fallback")
public CompletionStage<String> hello(Result result) throws IOException {
    switch (result) {
        case FAILURE:
            throw new IOException("Simulated IO error");
        case COMPLETE_EXCEPTIONALLY:
            CompletableFuture<String> future = new CompletableFuture<>();
            future.completeExceptionally(new IOException("Simulated IO error"));
            return future;
        default:
            return completedFuture("Hello");
    }
}
 
Example 24
@Asynchronous
@Retry(maxRetries = 2)
public CompletionStage<String> retry(Result result) throws IOException {
    COUNTER.incrementAndGet();
    switch (result) {
        case FAILURE:
            throw new IOException("Simulated IO error");
        case COMPLETE_EXCEPTIONALLY:
            CompletableFuture<String> future = new CompletableFuture<>();
            future.completeExceptionally(new IOException("Simulated IO error"));
            return future;
        default:
            return completedFuture("Hello");
    }
}
 
Example 25
@Asynchronous
@Retry(retryOn = IOException.class)
@CircuitBreaker(failOn = IOException.class, requestVolumeThreshold = 5, successThreshold = 3, delay = 2, delayUnit = ChronoUnit.SECONDS, failureRatio = 0.75)
@Fallback(fallbackMethod = "fallback", applyOn = { IOException.class, CircuitBreakerOpenException.class })
public CompletionStage<String> hello(int counter) throws IOException {
    // 3/4 requests trigger IOException
    if (counter % 4 != 0) {
        throw new IOException("Simulated IOException");
    }

    return completedFuture("Hello" + counter);
}
 
Example 26
@Asynchronous
@Retry(retryOn = IOException.class)
@CircuitBreaker(failOn = IOException.class, requestVolumeThreshold = 5, successThreshold = 3, delay = 2, delayUnit = ChronoUnit.SECONDS, failureRatio = 0.75)
@Fallback(fallbackMethod = "fallback", applyOn = { IOException.class, CircuitBreakerOpenException.class })
public CompletionStage<String> helloFailAsync(int counter) {
    // 3/4 requests trigger IOException
    if (counter % 4 != 0) {
        CompletableFuture<String> result = new CompletableFuture<>();
        result.completeExceptionally(new IOException("Simulated IOException"));
        return result;
    }

    return completedFuture("Hello" + counter);
}
 
Example 27
@Asynchronous
@Retry(maxRetries = 2)
public Future<String> retry(Result result) throws IOException {
    COUNTER.incrementAndGet();
    switch (result) {
        case FAILURE:
            throw new IOException("Simulated IO error");
        case COMPLETE_EXCEPTIONALLY:
            CompletableFuture<String> future = new CompletableFuture<>();
            future.completeExceptionally(new IOException("Simulated IO error"));
            return future;
        default:
            return completedFuture("Hello");
    }
}
 
Example 28
Source Project: quarkus   Source File: Service.java    License: Apache License 2.0 5 votes vote down vote up
@Asynchronous
@Fallback(fallbackMethod = "fallback")
@Timeout(value = 20L, unit = ChronoUnit.MILLIS)
@Retry(delay = 10L, maxRetries = 2)
public CompletionStage<String> faultTolerance() {
    tracer.buildSpan("ft").start().finish();
    throw new RuntimeException();
}
 
Example 29
/**
 * Service will retry a method returning a chained, running sequentially,
 * CompletionStage configured to completeExceptionally on all calls.
 *
 * @return a {@link CompletionStage}
 */
@Asynchronous
@Retry(maxRetries = 2)
public CompletionStage<String> serviceE() {
    countInvocationsServE++;

    // always fail
    return CompletableFuture.supplyAsync(doTask(null), executor)
        .thenCompose(s -> CompletableFuture.supplyAsync(doTask("Simulated error"), executor));
}
 
Example 30
/**
 * Returns a future which will be complete on method return if Asynchronous is disabled,
 * or incomplete if Asynchronous is enabled.
 *
 * @return Completed future
 */
@Asynchronous
public Future<String> asyncWaitThenReturn() {
    try {
        Thread.sleep(2000);
        return CompletableFuture.completedFuture("OK");
    }
    catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}