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

The following examples show how to use org.eclipse.microprofile.faulttolerance.Retry. 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
@Test
public void checkRetryVisibilityOnRetryServiceMethodSuppressLevel() throws Exception {
    Retry foundAnnotation;
    Method m = RetryOnClassServiceNoAnnotationOnOveriddenMethod.class.getDeclaredMethod("service");

    foundAnnotation = m.getDeclaredAnnotation(Retry.class);
    Assert.assertNull(foundAnnotation,
            "no Retry annotation should be found on RetryOnClassServiceNoAnnotationOnOveriddenMethod#service() via getDeclaredAnnotation()");

    foundAnnotation = m.getAnnotation(Retry.class);
    Assert.assertNull(foundAnnotation,
            "no Retry annotation should be found on RetryOnClassServiceNoAnnotationOnOveriddenMethod#service() via getAnnotation()");

    foundAnnotation = RetryOnClassServiceNoAnnotationOnOveriddenMethod.class.getDeclaredAnnotation(Retry.class);
    Assert.assertNull(foundAnnotation,
            "no Retry annotation should be found on RetryOnClassServiceNoAnnotationOnOveriddenMethod class via getDeclaredAnnotation()");

    foundAnnotation = RetryOnClassServiceNoAnnotationOnOveriddenMethod.class.getAnnotation(Retry.class);
    Assert.assertNotNull(foundAnnotation,
            "a Retry annotation should have been found because of inheritance on RetryOnClassServiceNoAnnotationOnOveriddenMethod " +
                    "class via getAnnotation()");
}
 
Example 2
/**
 * Configured to always time out and Retry until CircuitBreaker is triggered on 4th call.
 */
@CircuitBreaker(successThreshold = 2, requestVolumeThreshold = 4, failureRatio = 0.75, delay = 50000)
@Retry(retryOn = {RuntimeException.class, TimeoutException.class}, maxRetries = 7, maxDuration = 20000)
@Timeout(100) // Scaled via config
public 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 conn;
}
 
Example 3
/**
 * 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 4
/**
 * Retry twice in the event of failure, after which the fallback handler will be driven to write
 * the message to a fallback log.
 */
@Retry(maxRetries = 2)
@Fallback(NotificationFallbackHandler.class)
public String tweet(
    String message, Twitter twitter, Logger fbLogger, String handle, Logger logger)
    throws Exception {
  try {
    // Tweet the occasion (AcmeGifts Twitter account). If the message is
    // longer that 140 chars, the message is split.
    // For example: abcdef: "abc ..." "... def".
    List<String> msgList = preProcessMessage(message);
    for (String msg : msgList) {
      twitter.updateStatus(msg);
    }

    // Send a direct message to the occasion recipient.
    twitter.sendDirectMessage(handle, message);
  } catch (Exception e) {
    logger.log(Level.WARNING, "Tweet error", e);
    throw e;
  }

  return null;
}
 
Example 5
@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 6
/**
 * 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 7
@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 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
@Timeout(250)
@Fallback(fallbackMethod = "findAllStatic")
@Retry(maxRetries = 3)
public List<Customer> findAll() {

    randomSleep();

    return entityManager.createNamedQuery("Customers.findAll", Customer.class)
            .getResultList();

}
 
Example 10
@Deployment
public static WebArchive create() {
    ConfigAnnotationAsset config = new ConfigAnnotationAsset()
            .set(RetryConfigBean.class, "serviceMaxRetries", Retry.class, "maxRetries", "10")
            .set(RetryConfigBean.class, "serviceMaxDuration", Retry.class, "maxDuration", "1")
            .set(RetryConfigBean.class, "serviceMaxDuration", Retry.class, "durationUnit", "SECONDS")
            .set(RetryConfigBean.class, "serviceDelay", Retry.class, "delay", "2000")
            .set(RetryConfigBean.class, "serviceDelay", Retry.class, "delayUnit", "MICROS")
            .set(RetryConfigBean.class, "serviceRetryOn", Retry.class, "retryOn",
                 TestConfigExceptionA.class.getName() + "," + TestConfigExceptionB.class.getName())
            .set(RetryConfigBean.class, "serviceAbortOn", Retry.class, "abortOn",
                 TestConfigExceptionA.class.getName() + "," + TestConfigExceptionB1.class.getName())
            .set(RetryConfigBean.class, "serviceJitter", Retry.class, "jitter", "1")
            .set(RetryConfigBean.class, "serviceJitter", Retry.class, "jitterDelayUnit", "SECONDS");
    
    JavaArchive jar = ShrinkWrap.create(JavaArchive.class, "ftRetryConfig.jar")
            .addClasses(RetryConfigBean.class)
            .addClasses(TestConfigExceptionA.class, TestConfigExceptionB.class, TestConfigExceptionB1.class)
            .addPackage(Packages.UTILS)
            .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
            .addAsManifestResource(config, "microprofile-config.properties");
    
    WebArchive war = ShrinkWrap.create(WebArchive.class, "ftRetryConfig.war")
            .addAsLibrary(jar);
    
    return war;
}
 
Example 11
/**
 * 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 12
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 13
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 = 200L)
@Retry(delay = 100L, maxRetries = 2)
public String foo() {
    mockTracer.buildSpan("foo").start().finish();
    throw new RuntimeException();
}
 
Example 14
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 15
@Override
@Bulkhead(waitingTaskQueue = 5, value = 5)
@Asynchronous
@Retry(retryOn =
{ BulkheadException.class }, delay = 1, delayUnit = ChronoUnit.SECONDS, maxRetries = 10, maxDuration=999999)
public Future test(BackendTestDelegate action) throws InterruptedException {
    Utils.log("in business method of bean " + this.getClass().getName());
    return action.perform();
}
 
Example 16
/**
 * Has a CircuitBreaker and Retries on TimeoutException
 * <p>
 * The method should never throw a TimeoutException so the retry should have no effect
 * 
 * @param throwException whether this method should throw a TestException to simulate an application failure
 * @return string "OK"
 */
@CircuitBreaker(requestVolumeThreshold = 4, failureRatio = 0.75, delay = 1000)
@Retry(retryOn = TimeoutException.class, maxRetries = 20, delay = 200)
// Scaled via config
public String serviceWithRetryOnTimeout(boolean throwException) {
    if (throwException) {
        throw new TestException();
    }
    else {
        return "OK";
    }
}
 
Example 17
Source Project: smallrye-fault-tolerance   Source File: RetryTestBean.java    License: Apache License 2.0 5 votes vote down vote up
@Retry(retryOn = TimeoutException.class)
@Fallback(fallbackMethod = "fallback")
@Timeout(100L)
public String callWithRetryOnTimeoutException() {
    int attempt = this.attempt.getAndIncrement();
    if (attempt == 0) {
        sleep(5000L);
    }
    return "call" + attempt;
}
 
Example 18
Source Project: smallrye-fault-tolerance   Source File: RetryTestBean.java    License: Apache License 2.0 5 votes vote down vote up
@Retry(retryOn = OutOfMemoryError.class)
@Fallback(fallbackMethod = "fallback")
@Timeout(100L)
public String callWithRetryOnOutOfMemoryError() {
    int attempt = this.attempt.getAndIncrement();
    if (attempt == 0) {
        sleep(5000L);
    }
    return "call" + attempt;
}
 
Example 19
Source Project: smallrye-fault-tolerance   Source File: RetryTestBean.java    License: Apache License 2.0 5 votes vote down vote up
@Retry(retryOn = BulkheadException.class, delay = 500)
@Bulkhead(2)
@Fallback(fallbackMethod = "fallback")
public String callWithRetryOnBulkhead() {
    int attempt = this.attempt.getAndIncrement();
    // both first attempts should take long time
    // without @Asynchronous, the third attempt should fail right away with BulkheadException and should be retried
    // the third attempt should be retried in 500 ms, after the first two calls were processed and should be successful
    // no fallback should be called
    if (attempt < 2) {
        sleep(300L);
    }
    return "call" + attempt;
}
 
Example 20
/**
 * Service will retry a method returning a CompletionStage and configured to always completeExceptionally.
 *
 * @return a {@link CompletionStage}
 */
@Asynchronous
@Retry(maxRetries = 2)
public CompletionStage<String> serviceA() {
    countInvocationsServA++;
    // always fail
    CompletableFuture<String> future = new CompletableFuture<>();
    future.completeExceptionally(new IOException("Simulated error"));
    return future;
}
 
Example 21
/**
 * Service will retry a method returning CompletionStages but throwing an exception.
 * fail twice.
 *
 * @return a {@link CompletionStage}
 */
@Asynchronous
@Retry(maxRetries = 2)
public CompletionStage<String> serviceH() {
    countInvocationsServH++;
    // fails twice
    if (countInvocationsServH < 3) {
        throw new RuntimeException("Simulated error");
    }

    CompletableFuture<String> future = new CompletableFuture<>();
    future.complete("Success");
    return future;
}
 
Example 22
@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 23
/**
 * 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 24
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 25
/**
 * Service will retry a method returning a CompletionStage and configured to always completeExceptionally.
 *
 * @return a {@link CompletionStage}
 */
@Retry(maxRetries = 2)
public CompletionStage<String> serviceBFailException(final CompletionStage future) {
    countInvocationsServBFailException++;
    // always fail
    throw new RuntimeException("Simulated error");
}
 
Example 26
@Test
public void checkBaseRomRetryMissingOnMethod() throws Exception {
    Retry foundAnnotation;
    Method m = RetryOnMethodServiceNoAnnotationOnOverridedMethod.class.getDeclaredMethod("service");
    
    foundAnnotation = m.getDeclaredAnnotation(Retry.class);
    Assert.assertNull(foundAnnotation,
            "no Retry annotation should be found on RetryOnMethodServiceNoAnnotationOnOverridedMethod#service() " +
                    "via getDeclaredAnnotation()");

    foundAnnotation = m.getAnnotation(Retry.class);
    Assert.assertNull(foundAnnotation,
            "no Retry annotation should be found on RetryOnMethodServiceNoAnnotationOnOverridedMethod#service() via getAnnotation()");
}
 
Example 27
@Deployment
public static WebArchive deploy() {
    
    final Asset config = new DisableConfigAsset()
            .disable(Retry.class)
            .disable(CircuitBreaker.class)
            .disable(Timeout.class)
            .disable(Asynchronous.class)
            .disable(Fallback.class)
            .disable(Bulkhead.class)
            .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)
            .disable(DisableAnnotationClient.class, "failAndRetryOnce", Retry.class)
            .disable(DisableAnnotationClient.class, "failWithCircuitBreaker", CircuitBreaker.class)
            .disable(DisableAnnotationClient.class, "failWithTimeout", Timeout.class)
            .disable(DisableAnnotationClient.class, "asyncWaitThenReturn", Asynchronous.class)
            .disable(DisableAnnotationClient.class, "failRetryOnceThenFallback", Fallback.class)
            .disable(DisableAnnotationClient.class, "waitWithBulkhead", Bulkhead.class);

    final ConfigAnnotationAsset mpAnnotationConfig = new ConfigAnnotationAsset()
        .setValue(DisableAnnotationClient.class,"failWithTimeout",Timeout.class,getConfig().getTimeoutInStr(500))
        .mergeProperties(((DisableConfigAsset) config).getProps());

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

    WebArchive war = ShrinkWrap
        .create(WebArchive.class, "ftDisableGloballyEnableClassDisableMethod.war")
        .addAsLibrary(testJar);
    return war;
}
 
Example 28
@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)
           .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);
    
    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 29
@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)
           .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);
    
    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 30
/**
 * Invokes name service and increases the counter for invocations of serviceB
 * @return Always throws exception
 */
@Retry(maxRetries = 1)
@Fallback(StringFallbackHandler.class)
public String serviceB() {
    counterForInvokingServiceB++;
    return nameService();
}